/* jQuery plugins & support functions */
jQuery.fn.extend({
	scrollTo : function(offset, speed, easing) {
		return this.each(function() {
			var targetOffset = $(this).offset().top + offset || 0;
			$("html,body").animate({
				scrollTop : targetOffset
			}, speed, easing);
			return this;
		});
	},
	performLazyLoad : function(opts) {
		return this.each(function() {

			var options = $.extend(opts, jQuery.fn.performLazyLoad.defaultOptions);

			var $this = $(this);
			var start = new Date().getTime();
			if ($this.attr(options.attr)) {

				if (typeof options.before == "function")
					options.before();

				$this.monitorLoad(function() {
					var realWidth = $.browser.msie ? $this[0].offsetWidth : $this.clone().removeAttr("width").attr("width");
					var realHeight = $.browser.msie ? $this[0].offsetHeight : $this.clone().removeAttr("height").attr(
							"height");

					/* set dimensions, if not already done so in html */
					if ($this.attr("width") == realWidth && $this.attr("height") == realHeight) {
						$this.attr("width", realWidth);
						$this.attr("height", realHeight);
					}

					if (typeof options.after == "function")
						options.after();

					return this;
				});

				//console.log("lazy-loading: " + $this.attr(options.attr));

				$this.attr("src", $this.attr(options.attr)).removeAttr(options.attr);

			}
			return this;
		});
	},
	monitorLoad : function(callback) {
		return this.each(function() {
			var $this = $(this);
			return callback ? (this.nodeName == "IMG") ? $this.bind('load readystatechange', function(e) {
				if (this.complete || (this.readyState == 'complete' && e.type == 'readystatechange'))
					callback();
			}) : $this.bind('load', callback) : $this.trigger('load');
		});
	}
});
$.extend(jQuery.fn.performLazyLoad, {
	defaultOptions : {
		attr : "data-lazy-source",
		before : undefined,
		after : undefined
	}
});

/* side menu toggler */
var SideMenuToggler = function($togglers) {
	var showSideMenuItem = function() {
		var $orgParent = $(this);
		if (!$orgParent.hasClass("current")) {
			var $sub = $("ul", $orgParent);
			$orgParent.addClass("open");
			$sub.stop(false, true).slideDown(500);
		}
	}

	var hideSideMenuItem = function() {
		var $orgParent = $(this);
		if (!$orgParent.hasClass("current")) {
			var $sub = $("ul", $orgParent);
			$orgParent.removeClass("open");
			$sub.stop(false, true).slideUp(500);
		}
	}
	$togglers.hover(showSideMenuItem, hideSideMenuItem);
}

/* portfolio toggler */
var PortfolioToggler = function($togglers) {
	$togglers.click(function() {
		var $parentContainer = $(this).parent();
		var allItems = $(".portfolio>li");
		allItems.each(function() {
			var $this = $(this);
			var isClickedItem = $this[0] == $parentContainer[0];
			if (isClickedItem && !$this.hasClass("open")) {
				$parentContainer.slideUp(500, function() {
					$parentContainer.find(
							".images img[" + jQuery.fn.performLazyLoad.defaultOptions.attr + "]")
							.performLazyLoad();
					$(this).removeClass("closed").addClass("open").slideDown(1000, function() {
						$parentContainer.scrollTo(-20, 1000);
					});
				});
			} else if ($this.hasClass("open")) {
				$this.slideUp(250, function() {
					$(this).removeClass("open").addClass("closed").slideDown(500, function() {
						if (isClickedItem) {
							$parentContainer.scrollTo(-20, 500);
						}
					});
				});
			}
		});
	});
}

/* homepage slideshow */
//TODO: extend usage of sliderContainer
var HomepageSlider = function($sliderContainer) {
	var currentDelayPerSubSlide;
	var nrOfRevolutionsOfSubslider = 2;
	var subSlideTimeout = 5000;
	currentDelayPerSubSlide = subSlideTimeout;

	/* ie6 home slide css fixes */
	var fixSliderForIE6 = function() {
		if ($.browser.msie && $.browser.version < 7) {
			$("#homeslider ul>li>ul").addClass("homeslider_ul_li_ul");
			$("#homeslider>ul>li").addClass("homeslider_ul_li");
			$("#homeslider>ul>li>ul>li").addClass("homeslider_ul_li_ul_li");
			$("#homeslider .next").hover(function() {
				$(this).addClass("next_hover");
			}, function() {
				$(this).removeClass("next_hover");
			});
			$("#homeslider .previous").hover(function() {
				$(this).addClass("previous_hover");
			}, function() {
				$(this).removeClass("previous_hover");
			});
		}
	}

	if ($sliderContainer.length > 0) {

		fixSliderForIE6();

		if ($("#homeslider>ul>li").length <= 1) {
			$("#homeslider .next,#homeslider .previous").hide();
			$("#homeslider ul").width("auto");
			$("#homeslider ul").find("img").performLazyLoad();
			if ($.browser.msie && $.browser.version < 7) {
				$("#homeslider ul").find("img").css("position", "absolute");
			}

		} else {
			$("#homeslider>ul").cycle(
			{
				fx : "scrollHorz",
				timeoutFn : function(currSlideElement, nextSlideElement, options, forwardFlag) {
					var index = options.currSlide;
					return -100 + $("#homeslider>ul>li").eq(index).find("ul>li").length
							* currentDelayPerSubSlide * nrOfRevolutionsOfSubslider;
				},
				speed : 1000,
				pause : true,
				next : "#homeslider .next",
				prev : "#homeslider .previous",
				before : function(currSlideElement, nextSlideElement, options, forwardFlag) {

					$currSlideElement = $(currSlideElement);
					$nextSlideElement = $(nextSlideElement);

					/* lazy-load the bg of the next slide, pause main slider while it loads */
					$nextSlideElement.find(".slide-bg").performLazyLoad({
						before : function() {
							$nextSlideElement.parent("ul").cycle("pause");
						},
						after : function() {
							$nextSlideElement.parent("ul").cycle("resume");
						}
					});

					/* init next (==current for first 'before' event) (uninitialised) subslider before moving */
					/* unless there is only one slide: just preload it and do not init cycle */

					if (!$nextSlideElement.find("ul").attr("data-slider-initialised")) {
						if ($nextSlideElement.find("ul>li").length > 1) {
							$nextSlideElement.find("ul").cycle({

								fx : "fade",
								timeout : subSlideTimeout,
								speed : 1000,
								next : ".nextsub",
								prev : ".previoussub",
								pause : true,
								sliderExpr : "li",
								cleartype : false,
								cleartypeNoBg : false,
								fit : 1,
								width : ($.browser.msie) ? "618px" : undefined,
								height : ($.browser.msie) ? "245px" : undefined,
								containerResize : false,
								requeueOnImageNotLoaded : false,
								before : function(currSlideElement, nextSlideElement, options, forwardFlag) {
									currentDelayPerSubSlide = options.timeout;
									/* next subslide: lazy-load the next slide image and delay transition until image is loaded */
									$(nextSlideElement).find("img").performLazyLoad({
										before : function() {
											$currSlideElement.find("ul").cycle("pause");
										},
										after : function() {
											$currSlideElement.find("ul").cycle("resume");
										}
									});
								}
							}).attr("data-slider-initialised", true);
						} else {
							/* lazy-load the next subslides only image and hold transition for main slider */
							$nextSlideElement.find("ul>li img").performLazyLoad({
								before : function() {
									$nextSlideElement.parent("ul").cycle("pause");
								},
								after : function() {
									$nextSlideElement.parent("ul").cycle("resume");
								}
							});
						}
					}

					/* now proceed to next main slide: pause current subslide, start next subslide */
					if ($currSlideElement[0].id != $nextSlideElement[0].id) {
						/* make exception for first slide where next==current */
						if ($currSlideElement.find("ul").attr("data-slider-initialised"))
						/* only command initialised sliders (no slider for 1-item subslider */
							$currSlideElement.find("ul").cycle("pause");
						if ($nextSlideElement.find("ul").attr("data-slider-initialised"))
							$nextSlideElement.find("ul").cycle("resume");
					}

				}
			});
		}
	}
}

/* Portfolio 'Glider': mouse following slider */
var PortfolioGlider = function($gliderContainer) {
	$gliderContainer.mousemove(
			function(event) {
				var $this = $(this);
				var relMouseX = event.clientX - $this.offset().left;
				var visibleDivMiddle = this.offsetWidth / 2;
				var scrollableDistance = this.scrollWidth - 2 * visibleDivMiddle;
				var distanceFromVisibleCenter = relMouseX - visibleDivMiddle;
				var scrollStatWidth = $(".scrollStat", $this).outerWidth(true);

				var newScrollPos = (scrollableDistance / 2)
						+ (distanceFromVisibleCenter * ((scrollableDistance / 2) / visibleDivMiddle));
				var scrollStatOffset = (visibleDivMiddle * 2 - scrollStatWidth)
						* (newScrollPos / scrollableDistance);

				$this.stop(true, false).animate({
					scrollLeft : newScrollPos
				});
				$(".scrollStat", $this).css({
					left : newScrollPos + scrollStatOffset
				});

			}).mouseenter(function() {
		var scrollStatWidth = this.offsetWidth * (this.offsetWidth / this.scrollWidth);
		$(".scrollStat", $(this)).width(scrollStatWidth).fadeTo(1000, 0.75);

	}).mouseleave(function() {
		$(".scrollStat", $(this)).fadeOut();
	});
}

/* contact location photo 'slider' */
var ContactPhotoSlider = function($contactPhotoContainer) {
	$contactPhotoContainer.cycle({
		height : "173px",
		slideExpr : "img",
		timeout : 0,
		fx : "fade",
		speed : 500,
		pager : ".contact .photos .thumbs",
		pagerAnchorBuilder : function(idx, slide) {
			return '<img src="' + slide.src + '"" />';
		},
		activePagerClass : 'current'
	});
}

/* homepage(s): random jobs from CATS */
var VacancyRotator = function ($vacancyListContainer) {

    var viewDetailUrl = "http://vacature-detail.mirabeau.nl/careers/index.php?m=portal&a=details&jobOrderID=";
    var jobOrderUrl = "http://" + window.location.hostname + "/vacaturexml";

    if ($(document.body).hasClass("homepage")) { // disabled for now
        if ($vacancyListContainer.length > 0) {
            $.ajax({
                url: jobOrderUrl,
                dataType: ($.browser.msie) ? "text" : "xml",
                success: function (xmlData) {
                    var xml;

                    xml = $(xmlData);
                    if (xml && xml.find("response").attr("success") == "true") {
                        var $jobs = xml.find("item");
                        var jobsReturned = $jobs.length;
                        var maxJobsToShow = jobsReturned < 5 ? $jobs.length : 5;
                        $vacancyListContainer.html("");
                        var jobsShown = 0;

                        while (jobsShown < maxJobsToShow && jobsReturned > 0) {
                            var $job = $jobs.eq(jobsShown);
                            var $jobItem = $("<li><a></a></li>");
                            var jobTitle = $job.find("title").text();
                            var jobId = $job.find("item_id").text();
                            if (jobTitle == "Open Sollicitatie") {
                                jobsShown++;
                                maxJobsToShow++;
                                continue;
                            }
                            $jobItem.find("a").text(jobTitle);
                            $jobItem.find("a").attr({ title: jobTitle, href: viewDetailUrl + jobId });
                            $vacancyListContainer.append($jobItem);
                            jobsShown++;
                        }
                    }
                }
            });
        }
    }
}

/*
 * extend the validation framework (if present) with some methods that can/will be re-used on all pages
 */
function initValidatorDefaults() {
	if (jQuery.fn.validate) {
		$.extend(jQuery.validator, {
			errorPlacementFn : function(error, element) {
				var $status = element.parent("label").find("em");
				$status.html("").append(error);
				var $emsgContainer = $(".errormessages ul");
				var message = error.text();
				$emsgContainer.find("li." + element[0].name).remove();
				if (message != "") {
					$emsgContainer.append("<li class=\"" + element[0].name + "\">" + message + "</li>");
				}
				if ($emsgContainer.find("li").length == 0) {
					$(".errormessages").slideUp(500);
				}
			},
			invalidHandlerFn : function(formMap, validator) {
				var errorCount = validator.numberOfInvalids() || 0;
				if (errorCount > 0) {
					$(".errormessages").show();
					$(".errormessages ul").hide();
					$(".errormessages ul").slideDown(500);
				}
			},
			highlightFn : function(element, errorClass) {
				$(element).addClass(errorClass);
				$(element).parent("label").addClass(errorClass);
			},
			unhighlightFn : function(element, errorClass) {
				$(element).removeClass(errorClass);
				$(element).parent("label").removeClass(errorClass);
				$(".errormessages ul").find("li." + element.name).remove();
			},
			successFn : function(label) {
				label.html("").removeClass(this.errorClass).addClass(this.validClass);
			}
		});
	}
}

function initGATrackEvents() {
	if (typeof _gaq != "undefined") {
		// external links == all fully qualified urls excluding those to own domain
	    $("a[href^='http://']").not("a[href*='.mirabeau.nl'], .share a").click(function () {
			_gaq.push(["_trackEvent","link_external", $(this).attr("href"), window.location.hostname + window.location.pathname]);
			return true;
		});
		// mailto: links
		$("a[href^='mailto:']").click(function() {
			_gaq.push(["_trackEvent","link_mailto", $(this).attr("href")]);
			return true;
        });
        // social media buttons
        $(".share a").click(function () {
            _gaq.push(["_trackEvent", "social_button", this.id, window.location.hostname + window.location.pathname]);
           return true;
        });

		// slider nav arrows
		$("#homeslider span.next, #homeslider span.previous").click(function() {
			_gaq.push(["_trackEvent","slider_navigation","click_" + this.className, $("#homeslider ul a:visible").attr("href")]);
			return true;
		});

		// slider follow link
		$("#homeslider a").click(function() {
			_gaq.push(["_trackEvent","slider", $(this).attr("href")]);
			return true;
		});
		// portfolio toggles
		$(".portfolio h2").click(function() {
			_gaq.push(["_trackEvent","portfolio", $(this).find("strong").text()]);
			return true;
});

	}
}

function initFormValidation() {
	if ($("form.validated").length > 0) {
		$.getScript("/static/js/libs/jquery/metadata/2.1/jquery.metadata.js", function() {
			$.getScript("/static/js/libs/jquery/validate/1.5.5/jquery.validate.min.js", function() {
				initValidatorDefaults();

				$.metadata.setType("attr", "data-validate");

				var $valForm = $("form.validated");

				$valForm.validate({
					meta : "validate",
					errorClass : "invalid",
					errorElement : "span",
					focusCleanup : false,
					submitHandler : function(form) {
						form.submit();
					},
					errorPlacement : $.validator.errorPlacementFn,
					invalidHandler : $.validator.invalidHandlerFn,
					highlight : $.validator.highlightFn,
					unhighlight : $.validator.unhighlightFn,
					success : $.validator.successFn,
					debug : false
				});

			})
		});
	}
}
/* /jQuery plugins & support functions*/

$(document).ready(function() {
	new HomepageSlider($("#homeslider"));
//	new SideMenuToggler($(".aside ul.list>li"));
	new PortfolioToggler($(".portfolio h2"));
	new PortfolioGlider($(".portfolio li .images"));
	new ContactPhotoSlider($(".contact .photos .large"));
	new VacancyRotator($(".third.vacatures ul"));
	initGATrackEvents();
	initFormValidation();
});
