/**/
/*  This javascript file requires the jQuery library 
/*  Author: J.Oliemans
/**/

// plugin definition
$.fn.createPullDown = function (parent) {
	var delay = 0;
  parent = $(parent);
	parent.find("ul").css({ display: "none" });
	parent.find("li").hover(
    function() {
      var i, cols, t = $(this);
      t.find('ul:first').css({ visibility: "visible", display: "none" }).show(delay);
      
      // show the possible columns
      for (i = 2; i <= 5; i++) {
        cols = t.find("ul.floatcols-" + i);
        if (cols.length >= 0) {
          cols.css({ visibility: "visible", display: "none" }).show(delay);
        }
      }
    },
    function() {
      var i, cols, t = $(this);
      t.find('ul:first').css({ visibility: "hidden" });
      
      // hide the possible columns
      for (i = 2; i <= 5; i++) {
        cols = t.find("ul.floatcols-" + i);
        if (cols.length >= 0) {
          cols.css({ visibility: "hidden" });
        }
      }
    }
  );
};

// createpulldowns for the homeContainers
function createPulldownContainers() {
	$("a.quickLinksPulldown").each(function () {
		$(this)
      .next()
        .hide()
        .end()
      .click(function() {
        $(this).next().slideToggle(100).toggleClass('selected');
      });
	});
}

// createpulldowns for the testMenu
function createTestMenu() {
	$("a.testLabPulldownMenu").each(function () {
		$(this)
      .next()
        .hide()
        .end()
      .click(function() {
        $(this).next().slideToggle(100).toggleClass('testSelected');
      });
	});
	var node = $("a.active"), depth = 0;
	while (!node.hasClass("contextMenuList") && depth < 5) {
		node = node.parent();
		depth++;
	}
	node.prev().trigger("click");
}


// create tabs
function createTabs() {
	var firstTab = $("#productTabs > ul > li > a > span:first").text();
	if (firstTab.length > 0) {
		$("#productTabs > ul").tabs();
	}
}

function createFilterTabs() {
	// this shows the hidden second tabmenu
	$("#contextMenuContainer2").css({ position: "relative", left: 0 });

	$("#filterTabs > ul").hide().tabs().show();

	var tabs = $.makeArray($("#filterTabs ul li a span").map(function() { return $(this).text(); }));
  if (typeof strSelectedYear !== "undefined" && tab[0] === strSelectedYear) {
		$("#filterTabs > ul").tabs("select", 0);
  }
	if (typeof strSelectedYear !== "undefined" && tab[1] === strSelectedYear) {
		$("#filterTabs > ul").tabs("select", 1);
  }
}

function SwitchFAQ() {
  $("#faq-listing").show();
  $("#faq-detail").hide();
}

function calculateLocatienet(url, postcode) {
	if (postcode == "") {
		alert("U moet een postcode invullen.");
		return false;
	}

	var startPostcode = removeSpaces(postcode);
	var completeUrl = url +
	                    "&speedprofile=1&optfactor=90&detailmap=on&language=dutch&country_start=NL" +
	                    "&postcode_start=" + startPostcode;

	window.open(completeUrl, "Route", "width=800,height=600, menubar=no,status=no,directory=no,location=no,resizable=yes,scrollbars=yes,toolbar=no");

	return true;
}

//String functions
function removeSpaces(value) {
  return value.replace(/ /g, "");
}

// function for faq
function prepareFaq() {

	$('a.faq-detail').click(function () {
		if ($('div#faq-listing:visible')) {
			$('div#faq-listing').hide()
		}

		var tempUrl = $(this).attr('href');

		tempUrl = tempUrl.replace(/ /g, "%20");
		$('div#faq-detail').load(tempUrl);
		$('div#faq-detail').show();

		$('a.testFaqBack').click(function () {
			$('div#faq-detail').hide();
			$('a.testFaqBack').hide();
			$('div#faq-listing').show()
		});
		$('a.testFaqBack').show();

		return false;
	});

}

// show hide the third column for testlab iframe
function showHideColumn(value) {
	if ($('div#column3-sidebar')) {
		if (value == 'hide') {
			$('div#column3-sidebar').hide();
		} else if ((value == 'show')) {
			$('div#column3-sidebar').show();
		}
	}
}

function resizeMainHeader(maxLength) {
    var header = $('div#content h1');
    var headerText = header.text();
    var words = headerText.split(" ");
    var factor = 1;

    for (i = 0; i < words.length; i++) {
        if (words[i].length > maxLength) {
            var tempfactor = maxLength / words[i].length;
            //get scalefactor
            if (tempfactor < factor) {
                factor = tempfactor;
            }
        }
    }
    var currentSize = header.css('font-size');
    if (currentSize == null) {
       
    }
    else {
        var currentSizeNr = currentSize.substring(0, 2);
        var newSizeNr = Math.floor(currentSizeNr * factor);
        var newSize = String(newSizeNr) + "px";

        header.css('font-size', newSize);
    } 
}

// plugin definition
$.fn.createDoubleColumnList = function (parent) {
	//local
	/*var maxItemTwoClmn = 3;
	var maxItemThreeClmn = 6;
	var maxItemFourClmn = 9;
	var maxItemFiveClmn = 12;*/

	var maxItemTwoClmn = 10;
	var maxItemThreeClmn = 30;
	var maxItemFourClmn = 50;
	var maxItemFiveClmn = 70;

	var childrenUl = parent + " ul";
	var childrenLi = parent + " li ul li";

	$(parent).find("ul").each(function (i) {
		var listLength = $(this).find('li').length;
		var divLength = Math.floor(listLength / 2);

		if (listLength > maxItemTwoClmn && listLength < maxItemThreeClmn) {
			$(this).columns({ columns: 2 });
		}
		else if (listLength > maxItemThreeClmn && listLength < maxItemFourClmn) {
			$(this).columns({ columns: 3 });
		}
		else if (listLength > maxItemFourClmn && listLength < maxItemFiveClmn) {
			$(this).columns({ columns: 4 });
		}
		else if (listLength >= maxItemFiveClmn) {
			$(this).columns({ columns: 5 });
		}
	});

};

//$.fn.createStaticDoubleColumnList = function(parent)
//{
//    $(parent).find("ul").each(function (i) 
//    {
//        $(this).columns({ columns: 2 });
//    });
//};


function sitesLinkMenu() {
	//hide de list
	var list = $('a.sitesLink').next();
	list.hide();
	$('a.sitesLink').mouseover(function () {
		list.show();
	});

	$('a.sitesLink').mouseout(function () {
		list.hide();
	});

	list.mouseover(function () {
		list.show();
	});

	list.mouseout(function () {
		list.hide();
	});
}

// this function is called when the DOM is loaded
$(document).ready(function() {

    /* Reviews */
    
    var createLinkMoreHandler = function(openedHeight, closedHeight) {
      return function() {
        var link = $(this), open = link.data("open") === true;
        link.prev(".description").animate(
          { height: open ? closedHeight : openedHeight },
          400, "swing",
          function() {
            link[open ? "removeClass" : "addClass"]("link-more-close")
              .text(open ? "lees meer" : "sluit")
              .data("open", !open);
          }
        );
        return false;
      };
    };
    $(".hreview .description").each(function() {
      var description = $(this), openedHeight = description.height(), closedHeight;
      var maxLines = 5;
      description.css({ 
        overflow: "hidden",
        height: maxLines * 1.25 + "em"
      });
      closedHeight = description.height();
      if (closedHeight < openedHeight) {
        description
          .css({
            height: closedHeight
          })
          .after(
            $("<a href=\"#\" class=\"link-more\">lees meer</a>").click(
              createLinkMoreHandler(openedHeight, closedHeight)
            )
          );
      }
      else {
        description.css({ height: "" });
      }
    });
    
    var showMakereview = function() {
      var makereview = $(this);
      makereview.text(makereview.data("originaltext") || makereview.text()).addClass("link-makereview").removeClass("link-more link-more-close link-more-close-makereview");
    };
    var hideMakereview = function() {
      var makereview = $(this);
      makereview.data("originaltext", makereview.text()).text("sluit").removeClass("link-makereview").addClass("link-more link-more-close link-more-close-makereview");
    };

    window.initializeRatingSelect = function(initial) {
      var form = $(".form-review");
      $(".link-makereview").click(function() {
        var t = $(this), form = t.parent().find("> div > .form-review").css({ position: "relative", overflow: "hidden" }), showing = form.is(":visible");
        if (showing) {
          form.slideUp(400, "swing", function() {
            showMakereview.call(t);
          });
        }
        else {
          form.slideDown(400, "swing", function() {
            hideMakereview.call(t);
          });
        }
        return false;
      });
      if (!initial) {
        hideMakereview.call($(".link-makereview"));
      }
      
      form.find(".field-rating select").each(function() {
        var select = $(this), selection = Number(select.val()) || 0;
        
        var show = function(sel) {
          var t = $(this), w = t.width();
          sel = Math.ceil(sel / w * 5) * 20 + "%";
          t.children().width(sel);
        };
        var set = function(sel) {
          var w = $(this).width();
          show.call(this, sel);
          selection = sel;
          select.val(Math.max(Math.min(Math.ceil(sel / w * 5), 5), 1));
        };
        
        $(this)
          .css({
            visibility: "hidden",
            position: "absolute",
            left: "-999em"
          })
          .after(
            $("<p class=\"ratingtext\"><span class=\"rating\">.</span></p>")
              .each(function() {
                if (selection) {
                  $(this).children().width(selection * 20 + "%");
                }
              })
              .bind("mouseleave", function() { 
                show.call(this, selection);
              })
              .bind("mousemove", function(e) {
                show.call(this, e.layerX || e.offsetX);
              })
              .bind("click", function(e) {
                set.call(this, e.layerX || e.offsetX);
              })
          );
      });
    };
    window.initializeRatingSelect(true);
    
    
    $(".link-makereview + div > .form-review").hide();
    
    $(".trainingHeader .review-info a").click(function() {
      $("#detail-tabs a[href$=detail7]").not(this).click();
      return false;
    });
    
    
    $(".link-more-reviews").each(function() {
      var t = $(this), extrareviews = t.prevAll(".reviews").children("li:nth-child(1n+4)").hide();
      t.click(function() {
        var exp = "expanded";
        if (t.data(exp)) {
          t.data(exp, false).text("meer reviews");
          extrareviews.slideUp();
        }
        else {
          t.data(exp, true).text("sluit extra reviews");
          extrareviews.slideDown();
        }
        return false;
      });
    });
    
    
    /* Home-thema's */
    
    if (!$.support.opacity) { //Detect IE6-8
      $(".homeCrosslinks li:nth-child(2n)").addClass("even");
    }
    $(".homeCrosslinks").each(function() {
      var t = $(this), links = t.find("h3 a"), elements = t.find(".element"), visibles = { }, i;
      
      var animator = function(index, height, initial) {
        var after = function() {
          visibles[index] = height > 0;
          links.eq(index).parents("li:first")[visibles[index] ? "addClass" : "removeClass"]("open");
        };
        if (initial) {
          elements.eq(index).height(height);
          after();
        }
        else { 
          elements.eq(index).animate({ height: height }, 400, "swing", after);
        }
      };
      var createExpander = function(index) {
        var height = elements.eq(index).height();
        return function(e, data) {
          links.not(this).trigger("collapse", data);
          animator(index, height, data && data.initial === true);
        };
      };
      var createCollapser = function(index) {
        return function(e, data) {
          animator(index, 0, data && data.initial === true);
        };
      };
      var createClick = function(index) {
        return function(e) {
          if ($(e.target).is("a")) {
            $(this).trigger(visibles[index] ? "collapse" : "expand").trigger("blur");
            return false;
          }
        };
      };
      
      for (i = 0; i < links.length; i++) {
        links.eq(i)
          .bind("collapse", createCollapser(i))
          .bind("expand", createExpander(i))
          .bind("click", createClick(i));
      }
      
      //Initialize
      t.find("li")
        .not(
          t.find("li.open")
            .find("h3 a")
            .trigger("expand", { initial: true })
            .end()
        )
        .find("h3 a")
        .trigger("collapse", { initial: true });
    });
    
    
    /* PAO-accreditaties */
    $(".competenceFilter .explanation > div > ul").each(function() {
      var ul = $(this), li = $.makeArray($("li", this)), maxcol = 2, cols = [], i,
          colcount = li.length <= 5 ? 1 : maxcol,
          percol = li.length <= maxcol * 5 ? 5 : Math.ceil(li.length / maxcol);
          
      for (i = 0; i < colcount; i++) {
        cols[i] = $("<div/>").append($("<ul/>").append($(li.splice(0, percol)))).get(0);
      }
      ul.parent().before($(cols)).remove();
    });


    // initialize banner pop-up
    if ($('#ABMbanner')) {
        if ($('#ABMbanner').length != 0) {
            openABMbannerPopup();
        }
    }
    // initialize pulldown menu's				

    if ($('#nav')) {
        $("#nav ul").createPullDown("#nav");
    }
    if ($('#sitesNavigation')) {
        $("#sitesNavigation ul").createPullDown("#sitesNavigation");
    }
    if ($("#locationNavigation ul")) {
        $("#locationNavigation ul").createPullDown("#locationNavigation");
    }
    if ($("#contextMenuNoTabs ul")) {
        $("#contextMenuNoTabs ul").createPullDown("#contextMenuNoTabs");
    }
    if ($("#contextMenu ul")) {
        $("#contextMenu ul").createPullDown("#contextMenu");
    }
    if ($("#contextMenu2 ul")) {
        $("#contextMenu2 ul").createPullDown("#contextMenu2");
    }
    // tabbed submenu
    //contextMenu();
    //contextMenu2();

    // initialize tabs
    if ($("div#productTabs")) {
        if ($("div#productTabs").length > 0) {
            createTabs();
        }
    }
    // only run the tabs script if needed
    if ($("div#filterTabs")) {
        createFilterTabs();
    }

    if ($("a.quickLinksPulldown")) {
        createPulldownContainers();
    }

    if ($("a.testLabPulldownMenu")) {
        createTestMenu();
    }

    if ($("a.faq-detail")) {
        prepareFaq();
    }

    if ($('div#content h1')) {
        resizeMainHeader(22);
    }
    if ($('div#content h2')) {
        resizeMainHeader(22);
    }


    if ($("#contextMenu ul")) {
        $("#contextMenu ul").createDoubleColumnList("#contextMenu");
    }
    if ($("#contextMenu2 ul")) {
        $("#contextMenu2 ul").createDoubleColumnList("#contextMenu2");
    }
    if ($("#contextMenuNoTabs ul")) {
        $("#contextMenuNoTabs ul").createDoubleColumnList("#contextMenuNoTabs");
    }

    if ($('#tabs')) {
        $('#tabs').tabs();
    }

    if ($('ul.filterList ul')) {
        $('.filterList').columns({ columns: 2, columnClass: 'columns', columnWrapperClass: 'columns-wrapper' });
    }

/*
    if ($('ul.competenceList')) {
        $('.competenceList').columns({ columns: 3, columnClass: 'competence-columns', columnWrapperClass: 'competence-columns-wrapper' });
    }
*/

    if ($('ul.competenceTrainingList')) {
        $('.competenceTrainingList').columns({ columns: 2, columnClass: 'competence-training-columns', columnWrapperClass: 'competence-training-columns-wrapper ' });
    }

    if ($('a.sitesLink')) {
        sitesLinkMenu();
    }
    
    $('ul.competenceList').columns({ columns: 3, columnClass: 'competence-columns', columnWrapperClass: 'competence-columns-wrapper' });
    $('#detail-tabs').tabs();
    
    
    /* Navigatie in/uitklappen */
    
    $("#contextMenuList").each(function() {
      var allitems = $("li.haschildren", this);

      var control = {
        toggle: function(expand, items, initial) {
          var toggleClass = expand ? "addClass" : "removeClass", toggleSlide = expand ? "slideDown" : "slideUp", toggleShow = expand ? "show" : "hide";
          if (initial) {
            items.data("expanded", expand)[toggleClass]("open").children("ul")[toggleShow]();
          }
          else {
            items.children("ul")[toggleSlide](500, "swing", function() {
              items.data("expanded", expand)[toggleClass]("open");
            });
          }
        },
        expand: function(items, initial) {
          this.toggle(true, items, initial);
        },
        collapse: function(items, initial) {
          this.toggle(false, items, initial);
        }
      };
            
      allitems
        .click(function(e) {
          var t = $(this), target = $(e.target), collapse;
          if (target.is(".haschildren") || (target.is("a") && (/^#$/).test(target.attr("href")))) {
            collapse = allitems.not(t).filter(function() { return $(this).data("expanded"); });
            control.collapse(collapse, false);
            control.toggle(!t.data("expanded"), t, false);
          }
        });
      var opened = allitems.filter(".open:first");
      
      control.collapse(allitems.not(opened), true);
      if (opened.length) {
        control.expand(opened, true);
      }      
    });    
});

function openABMbannerPopup() {
	var target = $('a img', '#ABMbanner');
	var currentbanner = target.attr('src');
	var bannerwidth = target.width();
	var bannerheight = target.height();
	var lastDisplayed;

	var x = 0;

	var cookievalue = readCookie('ABMbanner');
	if (cookievalue != 'undefined') {
		if (cookievalue != currentbanner) {
			if (lastDisplayed == currentbanner) {
				return false;
			}
			tb_show("", "#TB_inline?height=" + bannerheight + "&width=" + bannerwidth + "&inlineId=ABMbanner&KeepThis=true");
			createCookie('ABMbanner', (currentbanner));
			lastDisplayed = currentbanner;
		}
		else {
			return false;
		}
	}

	function createCookie(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else {
			var expires = "";
		}

		document.cookie = name + "=" + value + expires + "; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name, "", -1);
	}

}
/*
function openFormHelp()
{
console.log("openFormHelp");
$( "<iframe width='400' height='500' ></iframe>" ).append( "TB_overlay" );
tb_show("", "#TB_inline?height=400&amp;width=500&amp;inlineId=vraagstukInfoContent");
}
*/



/* The function pageload is only called on pages containing an .Net UpdatePanel. */
function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
      $('ul.competenceList').columns({ columns: 3, columnClass: 'competence-columns', columnWrapperClass: 'competence-columns-wrapper' });
    }
    
    /*
    if ($('#detail-tabs').length) {

        $('#detail-tabs').tabs({
            add: function (event, ui) {
                $tabs.tabs('select', '#phcentercolumn_1_liTab4');
            }
        });

        if (args.get_isPartialLoad()) {
            var count = $('#filter4').parent().index() - 1;
            $('#detail-tabs').tabs('select', count)
        }

    }
    */
}



