jQuery.noConflict();

jQuery(document).ready(initPR);

// constructor function
function initPR() {
    jQuery("body").removeClass("noJs").addClass("activeJs");
    jQuery('.innerlabel', '#search').inputLabel();
    jQuery('.innerlabel', '#ctrPortalBottom .signup').inputLabel();
    if (jQuery('#SolutionTypeDropDownList').length) { initDDList(); }
    if (jQuery('#EmployeeFilterDropDownList').length) { initEFDDList(); }
    if (jQuery('#smoelenBoek').length) { initEmployees(); }
    if (jQuery('#searchEmployees').length) { initEmployeeSearch(); }
    if (jQuery('.scfForm li').length) { scrollToFormError() }
	if (!jQuery('.scfForm fieldset').length) { scrollToMessage() }
	

    jQuery(".scfSubmitButton").click(function(){
        if(jQuery(".scfValidationSummary:visible").length>0){
            scrollToFormError();
            return false;
        }
    })
    
    //add print button if needed
	if (jQuery('.print').length != 0) {jQuery('.print').printButton();}

    initNav();    
}

/* jQuery URLEncode/URLDecode extension from http://plugins.jquery.com/project/URLEncode
--------------------------------------------------------------------------*/
jQuery.extend({ URLEncode: function(c) {
	var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
	while (x < c.length) {
		var m = r.exec(c.substr(x));
		if (m != null && m.length > 1 && m[1] != '') {
			o += m[1]; x += m[1].length;
		} else {
			if (c[x] == ' ') o += '+'; else {
				var d = c.charCodeAt(x); var h = d.toString(16);
				o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
			} x++;
		} 
	} return o;
},
	URLDecode: function(s) {
		var o = s; var binVal, t; var r = /(%[^%]{2})/;
		while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
			b = parseInt(m[1].substr(1), 16);
			t = String.fromCharCode(b); o = o.replace(m[1], t);
		} return o;
	}
});

// hoofdnavigatie dropdown
function initNav() {
	
    jQuery("ul.mainnav li").hover(function() { //When trigger is clicked...
		
		//Following events are applied to the subnav itself (moving subnav up and down)
        jQuery(this).find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

        jQuery(this).hover(function() {
		}, function(){
		    jQuery(this).find("ul.subnav").slideUp('fast'); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() {
		    jQuery(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
		    jQuery(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});

}

//filteren open categorie binnen opleidingen
function initDDList() {
	var el = jQuery("#SolutionTypeDropDownList");
	jQuery("p a",el).attr('href', 'javascript:void(0)').click(
		function() {
			if (el.hasClass("open")) {
				jQuery(el).find("ul").slideUp("fast",function() {jQuery(this).hide().parent().toggleClass("open")});
			}
			else {
				jQuery(el).find("ul").slideDown("fast").show().end().toggleClass("open");
			}
		}
	);
}

// filteren op medewerkers binnen smoelenboek
function initEFDDList() {
    var el = jQuery("#EmployeeFilterDropDownList");
    jQuery("p a", el).attr('href', 'javascript:void(0)').click(
		function() {
		    if (el.hasClass("open")) {
		        jQuery(el).find("ul").slideUp("fast", function() { jQuery(this).hide().parent().toggleClass("open") });
		    }
		    else {
		        jQuery(el).find("ul").slideDown("fast").show().end().toggleClass("open");
		    }
		}
	);
}

// AJAX search for employees 
function initEmployeeSearch() {
    var target = jQuery('#searchEmployees');
    //target.attr({ openstate: 'closed' });

    // Bind searchbox
    jQuery('#searchtext').live('keyup', function() {
        //var text = jQuery.URLEncode(jQuery(this).val());
        var text = jQuery(this).val();
        getWords(text);
    });
    
    // Build ResultBox
   target.append(
		jQuery(document.createElement('div'))
			.attr('id', 'autocomplete')
			.append(jQuery(document.createTextNode("close")))
			.click(function(){
				hideResultBox();
			})
	)
	.css({'display':'block'});
	
	function hideResultBox() {
		//console.log("close");
	}

    function getWords(text) {
        // Call page method, the ID = the sitecore id of the Smoelenboek item (Wie wij zijn)
        jQuery.ajax({
            type: "POST",
            url: "/sitecore/service/Smoelenboek.asmx/GetNames",
            data: '{searchtext: "' + text + '", id: "{BBE41DD0-9E2A-4CE6-862C-993EF5DF0DDB}"}',
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg, status) {
                showResults(msg.d);
                //console.log(msg.d);
            },
            error: function(xhr, msg, e) {
                alert(msg);
            }
        });
    }
    
    function showResults(result) {
		
		var container = jQuery('#autocomplete');
		container.empty();
		if (result == "") {
			container.css({'display':'block'}).append('<p>Geen resultaten gevonden</p>');
			//container.hide();
		} else {
			container.css({'display':'block'});
			container.append('<a class="floatright" href="#">X</a>').bind('click', function() { jQuery('#autocomplete').hide(); });
			jQuery.each(result, function() {
				container.append('<a href="/Wie%20wij%20zijn/Pink-ers.aspx?name=' + this + '">' + this + '</a>');
			});
		}
    }
}

//smoelenboek en smoelen-detail lightbox
function initEmployees() {
	
	var target = jQuery('#smoelenBoek ul');
	
	target.append(
		jQuery(document.createElement('li'))
			.attr('class','fog')
	);
	target.after(
		jQuery(document.createElement('div'))
			.attr('id', 'detail_popup')
	);
	
	// show popup onload
	jQuery('.popup:first',target).each(function() {
		showDetail(jQuery('.bio',this)); 
	});
		
	function showDetail(caller) {
		raiseFog();
		jQuery("#detail_popup")
			.html(jQuery(caller).html())
			.append(
				jQuery(document.createElement('div'))
					.attr('id', 'close_popup')
					.append(jQuery(document.createTextNode("close")))
					.click(function(){
						hideDetail();
					})
			)
			.css({'display':'block','top':'2px'});
	}
	

	jQuery('li',target).each(function(){
		//jQuery('.bio',this).hide();
		jQuery('a.smallThumbnail',this)
			.tooltip({ 
				track: true, 
				delay: 0, 
				showURL: false, 
				showBody: " - ", 
				fade: 250 
			})
			.attr('href', 'javascript:void(0)')
			.click(function(){
				showDetail(jQuery(this).next()); 
			});
	})
	
	function hideDetail() {
		lowerFog();
		jQuery("#detail_popup")
			.css({'display':'none'});
	}

	function raiseFog() { 
		var targetheight = target.height()+"px";
		jQuery(".fog").css({'display':'block','height':targetheight});
	}
	function lowerFog() { 
		jQuery(".fog").css({'display':'none'});
	}
}


 // function to scroll to a formformarketeers form when a error is thrown
function scrollToFormError() {   
	var formTop = jQuery(".scfForm li:first").position().top
	self.scrollTo(0, formTop)
}

function scrollToMessage(){
	if(jQuery(".scfForm").text().length===0){return false}
	if(jQuery(".scfForm .scfSubmitButtonBorder").length){return false};
    jQuery(".scfForm").addClass("message");
    var formTop = jQuery(".scfForm").position().top
    self.scrollTo(0, formTop)
}
