// NS Er op uit

$(document).ready(function() {

	// js-enabled
	$("body").addClass("js-enabled");	
	
	// init stuff
	init(document);
	
	// create submit buttons
	$(".buttons input.submit", document).addSubmit();
	
	// create nice dropdown
	$("#category").selectbox({debug: false});
	
	// create collapsable panels
	$("#search", document).collapsablePanel(true);
	$("#googlemap, #neighbourhood, #relateditems, #campaign-information, #send-a-friend", document).collapsablePanel(true);
	
	// create helpers
	$("a.helper-map").openHelperMap("Selecteer een provincie", "helper-map-nl");
	$("#travelplanner a.helper-calendar").openHelperCalendar("Selecteer een datum", false);
	$("#search a.helper-calendar").openHelperCalendar("Selecteer een datum", true);

	// photo galleries
	$("a.photogallery").openPhotoGallery();

	// slider
	$(".priceslider").priceSlider("filter-maxfee");
	
	// campaign-information
	$('#campaign-information .collapse-item:first').addClass('first');
	$('#campaign-information .collapse-item:last').addClass('last');


	var carousel = new NSCarousel('#carousel', {
		scroll: 1,
		preload: 4,
		wrap: 'last',
		auto: 5
	});	
});

Function.prototype.bind = function(scope) {
	var method = this;
	return function() {
		return method.apply(scope, arguments);
	}
}

function init(context) {
	initBoxes(context);
	initOutings(context);
	initPromos(context);
	initFramedImages(context);
	initDetailGallery(context);
	initFormSubElements(context);
	initStarRating(context);
}

/* fancy-boxes */
function initBoxes (context) {
	//only if given context exists
	if (context) {
		// add cosmetic divs
		$("div.box",context).each(function() {
			$(this).prepend("<div class=\"top\"></div>");
			$(this).append("<div class=\"bottom\"></div>");
		});
	}
}

// stuff that handles the star rating
function initStarRating(context) {
	$("ul.star-rating li a").click(function(event) {
		var points = $(this).attr("rel");
		$("#points").val(points);
		// set active star-rating-active
		$(this).parent("li").parent("ul").find("li").removeClass("star-rating-active");
		$(this).parent("li").addClass("star-rating-active");
		// stop event
		event.preventDefault();
	});
}

/* outings in search result */
function initOutings (context) {
	// make hover classes
	$("div.outing",context).hover(
		function() {
			$(this).addClass("outinghover");
		},
		function() {
			$(this).removeClass("outinghover");
		}
	);
	// make hover classes
	$("div.outing div.hovercontainer",context).hover(
		function() {
			$(this).addClass("hover");
		},
		function() {
			$(this).removeClass("hover");
		}
	);
	// same effect for keyboard focus
	$("div.outing",context).focus(
		function() {
			$(this).addClass("outinghover");
		}
	);
	$("div.outing",context).blur(
		function() {
			$(this).removeClass("outinghover");
		}
	);
	$("div.outing div.hovercontainer",context).focus(
		function() {
			$(this).addClass("hover");
		}
	);
	$("div.outing div.hovercontainer",context).blur(
		function() {
			$(this).removeClass("hover");
		}
	);
	// add click on the body
	$("div.outing div.body",context).click(function(event) {
		var target = event.target;
		if(!(target.className.match("addtofavorites") || target.className.match("removefromfavorites"))) {
			var url = $(this).find("a.button").filter(".more").attr("href");
			
			document.location = url;
		}
	});
}

/* promos (agenda, special offers) */
function initPromos (context) {
	$(".promo",context).each(function() {
		$(this).hover(
			function() {
				$(this).addClass("hover")
			},
			function() {
				$(this).removeClass("hover")
			}
		);
		$(this).click(function(event) {
			var url = $(this).find("a").attr("href");
			
			document.location = url;
		});
	});
}

/* set a frame on thumbnailed images */
function initFramedImages (context) {
	$("img.framed",context).each(function() {
		$(this).wrap("<span></span>");
		$(this).parent().attr("class", $(this).attr("class"));
		$(this).attr("class","");
		$(this).parent().append("<span class=\"frame\"></span>");
	});
}

/* photo gallery on detail pages */
function initDetailGallery (context) {
	$("#detail-gallery .thumbs a",context).each(function() {
		$(this).click(function(event) {
			var src = $(this).attr("href");
			var alt = $("img",$(this)).attr("alt");
			var largeImage = $(".top img",$(this).parent().parent().parent().parent());
			largeImage.attr("src",src);
			largeImage.attr("alt",alt);
			// reset 'current' state of all thumbs
			$("li",$(this).parent().parent()).each(function() {
				$(this).removeClass("current");
			});
			// set 'current' state
			$(this).parent().addClass("current");
			event.preventDefault();
		});
	});
}

/* add various behaviour to form sub-elements */
initFormSubElements = function (context) {
	initFocusValues(context);
	initTitleLabels(context);
	initInFieldLabels(context);
	/* form submit */
	$("form").submit(function(event) {
		$("label.infield",$(this)).each(function() {
			var label = $(this);
			var target = $("#" + label.attr("for"));
			if(target.length > 0) {
				if(target.attr("type") == "text" || target.get(0).tagName == "TEXTAREA") {
					if(target.val() == target.attr("title")) target.val("");
				}
			}
		});
	});	
}

/* select text field's content when focussed on */
initFocusValues = function (context) {
	$(".focusvalue",context).each(function() {
		$(this).focus(function() {
			$(this).select();
		});
	});
}

/* use title as in-field label */
initTitleLabels = function (context) {
	$(".titlelabel",context).each(function() {
		if($(this).attr("type") == "text") {
			if($(this).val() == "" || $(this).val() == $(this).attr("title")) {
				$(this).val($(this).attr("title"));
				$(this).addClass("labeled");
			}
			$(this).focus(function() {
				if($(this).val() == $(this).attr("title")) {
					$(this).val("");
					$(this).removeClass("labeled");
				}
			});
			$(this).blur(function() {
				if($(this).val() == "") {
					$(this).val($(this).attr("title"));
					$(this).addClass("labeled");
				}
			});
		}
	});
}

/* place (hidden) label text inside form sub elements  */
initInFieldLabels = function (context) {
	$("label.infield",context).each(function() {
		var label = $(this);
		var target = $("#" + label.attr("for"));
		
		if(target.length > 0) {
			if (target.children('option').length > 0) {
				target.children('option').get(0).className = "labeled";
			}
		
			if(target.get().tagName == "SELECT") {
			
				target.prepend("<option class=\"labeled\" value=\"\">" + label.text() + "</option>");
			}
			if(target.attr("type") == "text" || target.get(0).tagName == "TEXTAREA") {
				if(target.val() == "" || target.val() == label.text()) {
					target.val(label.text());
					target.addClass("labeled");
				}
				target.attr("title",label.text());
				target.focus(function() {
					if(target.val() == target.attr("title")) {
						target.val("");
						target.removeClass("labeled");
					}
				});
				target.blur(function() {
					if(target.val() == "") {
						target.val(target.attr("title"));
						target.addClass("labeled");
					}
				});
			}
		}
	});
}

function NSCarousel(selector, settings) {
	this.preload = settings.preload;
	this.props = $.extend({}, settings, {
		initCallback: this.init.bind(this),
		itemVisibleInCallback: {
			onBeforeAnimation: this.before.bind(this)
		}
	});

	jQuery(selector).jcarousel(this.props);
	
}

NSCarousel.prototype = {
	init:function(carousel) {
		this.resource = $('link[rel=carousel]').attr('href');
	},
	
	before:function(carousel, item, i, state, evt) {
		var size = carousel.options.size;
		var next = (i % size) + 1;
		var nextItem = carousel.get(next)[0];

		var html = /[<>]/mg;
		if(nextItem && !(html.test(nextItem.innerHTML))){
			this.load(nextItem, this.preload);
		}
	},

	load:function(item, amount) {
		console.log('hier')
		var siblings = $(item.parentNode).find('li');
		var index = siblings.index(item);
		var total = siblings.length;
		var post = [];
		
		// get the next [amount] items and add store their ids
		for(var i=0; i<amount; i++) {
			// n wraps around total; 49, 50, 1, 2
			var n = (total + index + i) % total;
			var el = siblings.eq(n);
			var id = el[0].id || el[0].jcarouselid;
			if(id) {
				post.push('id=' + id);
			}
		}
		
		// and load it
		$.get(
			this.resource, 
			post.join('&'), 
			this.handleResponse.bind(this), 
			'json'
		);
	},

	handleResponse:function(response) {
		
		var items = response.items;
		for(var i=0; i<items.length; i++) {
			this.parseItem(items[i]);
		}
	},

	parseItem:function(item) {
		// write the html to the items with the correct id, and the jcarsouselid ghosts
		$('[jcarouselid="' + item.id + '"], [id="' + item.id + '"]').html(item.html);
	}
};

