var ie  = $.browser.msie;
var ie6 = $.browser.msie && ($.browser.version == "6.0");

$(function() {
 
  $('html').removeClass('no-js');
  $('.js-hidden').hide();


  //$('body').prepend('<a href="/feedback/" class="feedback">Beoordeel kiesBeter.nl</a>');

	$.extend({

		/* converts classname consisting of equals sign-separated label value pairs and returns object */
		classToObject: function(classname) {
			var input = (classname) ? classname.split(" ") : [];
			var obj = {};

			$.each(input, function(i, val) {
				var label = val.substring(0, val.indexOf("="));
				var value = val.substring(val.indexOf("=") + 1);
				if (label == "") return;
				if (label == "params") {
					var params = eval(val);
					obj.params = {};
					for (p in params) {
						obj.params[p] = escape(params[p]);
					}
				} else {
					obj[label] = (value == "true" || value == "false") ? eval(value) : value;
				}
			});

			return obj;
		},

		/* converts supplied object to classname string */
		objectToClass: function(obj) {
			var input = (obj) ? obj : {};
			var str = "";

			$.each(obj, function(i, prop) {
				if (i == "params") {
					for (p in prop) {
						str += ((p == "") ? prop[p] : p + "=" + prop[p]) + " ";
					}
				} else {
					str += ((i == "") ? prop : i + "=" + prop) + " ";
				}
			});

			str = str.substring(0, str.length - 1);

			return str;
		},

		/* converts querystring parameters and returns object */
		queryToObject: function(qs) {
			var input = (qs) ? qs.split("&") : [];
			var obj = {};

			$.each(input, function(i, segment) {
				var p = segment.split("=");
				obj[p[0]] = p[1];
			});

			return obj;
		},

		/* converts object to querystring parameters and returns string */
		objectToQuery: function(obj) {
			var input = (obj) ? obj : {};
			var qs = "";

			$.each(obj, function(i, segment) {
				qs += i + "=" + segment + "&";
			});

			qs = qs.substring(0, qs.length - 1);

			return qs;
		},

		/* creates an inline popup */
		popup: function(text, event, options) {
			var popup;
			var config = {};
			//console.log(event);
			$.extend(config, options);
			if ($("#popup").length == 0) {
        popupoverlay= $("<div id='popupoverlay'></div>").appendTo($("body"));
        if(ie) {
          popupoverlay.attr('style','filter: alpha(opacity=30); ');
        } else {
          popupoverlay.attr('style','opacity: 0.3; ');
        }
				popup = $("<div id='popup'></div>").appendTo($("body"));
				
				if(typeof config.cssid == "undefined") {
				  config.cssid= "popup_content";
				}
				
				popup.append($("<h4>Uitleg van begrip</h4><div id='"+config.cssid+"'></div>"), $("<button id='closer'>sluiten</button>").click(function() {
					popup.remove();
					popupoverlay.remove();
				}));
			} else {
				popup = $("#popup");
			}
			
			
			//popup.find("h4").text(config.title || $(event.target).parent("a").attr("title"));
			
			if(config.title!="") {
			 popup.find("h4").text(config.title);
			}
			popup.find("#"+config.cssid).html(text);

			windowHeight = $(window).height();
			scroll_pos = _get_scroll();

			projectedTop = scroll_pos['scrollTop'] + ((windowHeight/2) - (popup.height()/2));

			popup.css({
				left: ($(window).width() - popup.width()) / 2,
				//top: event.pageY - popup.height() / 2,
				top: projectedTop,
				zIndex: 999
			}).fadeIn("slow", function() {
				popup.css("top", projectedTop);
				//if (popup.offset().top < 0) {
				//	popup.css("top", popup.offset().top + Math.abs(popup.offset().top) + 10);
				//}
			});
			
			popupoverlay.show();
		},

		/* scrollable tables */
		tableScroller: function(expr, initHeight) {

			$(expr).each(function(index, table) {

				if ($(expr).find("tr").length > 0) {

					var thead   = $(this).find("thead");
					var caption = $("<caption>Gefixeerde rijkoppen voor " + $(this).find("caption").text().toLowerCase() + "</caption>");
					var header  = $("<table class='wrap-header'></table>").addClass($(this).attr("class")).append(caption, thead.clone());
					var wheight = initHeight || 400;
					var wrapper = $("<div class='wrapper'></div>").css({
						height: wheight
					});

					thead.hide();
					$(this).wrap(wrapper);
					header.insertBefore($(this).parent("div.wrapper"));

				}

			});
		}
	});

	function _get_scroll(){
		if (self.pageYOffset) {
			return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
		} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
			return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};
		} else if (document.body) {// all other Explorers
			return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
		};
	};

	var menuItemToShow;
	var menuItemToHide;
	
	var menuItemHover = false;
	var submenuHover = false;
	var menuCollapsed = true;
	
	$("div#navigation > ul > li > div.submenu").attr("style", "visibility: hidden");
	
	$("div#navigation > ul > li > a").mouseover(function() {
	
		setTimeout(function() { menuItemHover = true; }, 0);
		
		if (menuItemToShow != null) {
			menuItemToHide = menuItemToShow;
		}
			
		menuItemToShow = $(this).next();
		
		if (menuItemToHide != null && menuItemToShow != null && menuItemToHide[0] == menuItemToShow[0])
			menuItemToHide = null;
		
		setTimeout(
			function() { 
			
				if (menuItemHover && menuItemToShow != null) { 
					menuItemToShow.attr("style", "visibility: visible");
					menuItemToShow.show(); 
					menuCollapsed = false; 
					
				}
				
				if (menuItemToHide != null) {
					menuItemToHide.hide();
				}
							
				
			}, (menuCollapsed ? 500 : 0));

			

			
	});

				
	$("div#navigation > ul > li > a").mouseout(function() {
		setTimeout(function() { menuItemHover = false }, 0);

		setTimeout(function() { if (!menuItemHover && !submenuHover) { $("div#navigation > ul > li > div.submenu").hide(); menuCollapsed = true; } }, 500);
		
	});
	
	$("div#navigation > ul > li > div.submenu").mouseenter(function() {
		setTimeout(function() { submenuHover = true; }, 0);
	});
	
	$("div#navigation > ul > li > div.submenu").mouseleave(function() {
		setTimeout(function() { submenuHover = false; }, 0);
		
		setTimeout(function() { if (!menuItemHover && !submenuHover) { $("div#navigation > ul > li > div.submenu").hide(); menuCollapsed = true; } }, 500);
	});
	
	

	/* open review link in new window */
	$("#pageoptions #review a").click(function() {
		window.open($(this).attr("href"));
		return false;
	});


	/* buttons */
	$("button, input.button").live("mouseover", function() {
		$(this).addClass("highlight");
	}).live("mouseout", function() {
		$(this).removeClass("highlight");
	});

	/* begrippen popups */
	$("a.termpopup, a.popup, a.kb_bh_richtooltip").attr('title', '(opent in een popup-venster)');
	$("a.termpopup, a.popup, a.kb_bh_richtooltip").live("click", function(e) {

		var url = $(this).attr("href");
		var result = new RegExp("(begrippen|begrippennietinlijst|begrippen-los)/([^/]*)/(default.aspx)?$", "i").exec(url);
		
		if (result) {
			$.ajax({
				type: "POST",
				url: "/KBServices/TermService.svc/GetTerm",
				data: '{"friendlyName": "' + result[2] + '"}',
				dataType: "json",
				contentType: "application/json; charset=utf-8",
				success: function(response) {
					text = "<h5>" + response.d.Name + "</h5>" + response.d.Content;
					$.popup(text, e);
				},
				error: function(request, statusmsg, error) {
					text = "<h5>Tekst niet gevonden.</h5>";
					$.popup(text, e, { title: "Foutmelding" });
				}
			});

			e.preventDefault();
		}
	});

	/* inline popups naar verborgen content op de pagina */
  $("a.inlinepopup").each( function() {
    $($(this).attr("href")).hide(); // Verberg het element met een id wat gelijk is aan de href van de link
  });
	
	$("a.inlinepopup").live("click", function(e) {
		var url = $(this).attr("href");
		if($(url).is('*')) {
		  $.popup($(url).text(), e, { title: $(this).attr('title') });
		}

		e.preventDefault();
	});


	$("a.feedback").live("click", function(e) {
		var url = $(this).attr("href");

			$.ajax({
				type: "GET",
				url: url,
				success: function(response) {
				var action= $("a.feedback").attr('href');
  		  var title= $(response).find('h1')[0].innerHTML;
  			var content= $(response).find('.wizardview').find('.container');
				var submitBtn= $(response).find('.wizardview').find('.controls').find('.next');
				var form = $('<form id="feedbackForm" action="' + action + '" method="post"></form>').append(content).append(submitBtn);
					$.popup(form, e, { title: title , cssid: "beoordeel-content" } );
          $("div.tab_container > div.tab").hide();
          $("div.tabs li.current a").click();
				},
				error: function(request, statusmsg, error) {
					text = "<h5>Tekst niet gevonden.</h5>";
					$.popup(text, e, { title: "Foutmelding" });
					
				}
			});

			e.preventDefault();
	});
	


	/* faq */
	$("div.siteresult dd.hidden, div.kb_index_alpha_anchor_result dd.hidden").hide();
	
	$("div.siteresult dd").removeClass("hidden");
	$("div.siteresult dd").hide();

	$("div.siteresult input.kb_bh_swapdeflistbybutton, div.kb_index_alpha_anchor_result input.kb_bh_swapdeflistbybutton").click(function() {
		$(this).parent("dt").toggleClass("open").next("dd").toggle();
	});
	
	
	
	$('#tab_beoordeel ol a, #tab_fout ol a').live('click', function(e) {
    $("#"+$(this).attr('rel')).attr("checked", "checked"); 
    
    aantal= $(this).text();
    $(this).closest('ol').slideUp().nextAll('textarea').slideDown().before("<p>"+aantal+"</p>");
    return false;
  }); 
	
	
	
});

function strstr(haystack, needle, bool) {

    var pos = 0;

    haystack += "";
    pos = haystack.indexOf(needle); 

    if (pos == -1) {
        return false;
    } else {
        if (bool) {
            return haystack.substr(0, pos);
        } else {
            return haystack.slice(pos);
        }
    }
}



/* sitestat */
function sitestat(ns_l) {
	ns_l += "&amp;ns__t=" + (new Date()).getTime();
	ns_pixelUrl = ns_l;
	ns_0 = document.referrer;
	ns_0 = (ns_0.lastIndexOf('/') == ns_0.length - 1) ? ns_0.substring(ns_0.lastIndexOf('/'),0) : ns_0;
	if (ns_0.length > 0) {
		ns_l += "&amp;ns_referrer=" + escape(ns_0);
	}
	if (document.images) {
		ns_1 = new Image();
		ns_1.src = ns_l;
	} else {
		document.write("<img src='" + ns_l + "' width='1' height='1' alt=''>");
	}
}
