
// this is the plugin code. You can copy/paste it at the bottom of the jquery.js library file
(function($) {
	 $.fn.tooltip = function(options) {
		 $('body').append('<div id="sstt" class="jTooltip default" style="display:none;"></div>');
		 if (typeof options == 'undefined') options = {};
		 this.live('mousemove', function(e) {

			 var att = 'attribute' in options && $(this).attr(options.attribute);
			 if(!att) att = $(this).attr('rel');

			 var bbox = 'bbox' in options && options.bbox;
			 if (!bbox) bbox = $(document);

			 if ('text' in options && options.text) att = options.text;

			 if ($(this).is('img')) att = $(this).attr('rel');
			 if ($(this).is('a')) att = $(this).attr('rel');

			 var elem = $('#sstt'),csstxt = elem.css('cssText'),ew=elem.width(),dw=bbox.width(),px=e.pageX+10,py=e.pageY+10;
			 elem.html(att);
			 var eloffset = dw > px+ew &&
			 elem.css('cssText', csstxt+';position:absolute;top:'+py+'px;left:'+px+'px;display:block');

			 !eloffset &&
			 elem.css('cssText', csstxt+';position:absolute;top:'+py+'px;left:'+(dw-ew)+'px;display:block');
		 });
		 this.live('mouseout', function() {
			$('#sstt').hide();
		 });
	 };
})($);


/**
 * Check if date validates to a regexp
 * 
 * @param datStr The date to check
 */
function checkDate(dateStr){
	var regExp = /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d$/;
	return regExp.test(dateStr);
}

/**
 * Check if a phonenumber validates to a regexp
 */
function checkPhonenumber(phoneNumber) {
	var regExp = /(\+)?([-\._\(\) ]?[\d]{3,20}[-\._\(\) ]?){2,10}/;
	return regExp.test(phoneNumber);
}

/**
 * Check if a e-mailaddress validates to a regexp
 */
function checkEmailaddress(emailaddress) {
	var regExp = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
	return regExp.test(emailaddress);
}


function saveTelEmail(errMsgTel, errMsgEmail) {
	if(savePhoneNumbers(errMsgTel) && saveEmailAddresses(errMsgEmail)){
		$('#update_phoneemail').submit();
	}
}

/**
 * Check field before submit phonenumber form
 * 
 * @param errMsg The message to display when something goes wrong
 */
function savePhoneNumbers(errMsg) {
	var inputFields = $('input.phoneInput','#update_phoneemail');
	var mayReturn = true;
	inputFields.each(function(phoneNumber){
		if($(this).val() != '') {
			if(!checkPhonenumber($(this).val()) && $(this).val().indexOf('**') == '-1') {
				alert(errMsg);
				mayReturn = false;
				$(this).removeClass('error').addClass('error');
				$(this).focus();
			}
		}
	});
	
	if(mayReturn){
		return true;
	} else {
		return false;
	}
}

/**
 * Check field before submit e-mailaddresses form
 * 
 * @param errMsg The message to display when something goes wrong
 */
function saveEmailAddresses(errMsg) {
	var inputFields = $('input.emailInput','#update_phoneemail');
	var mayReturn = true;
	inputFields.each(function(emailaddress){
		if($(this).val() != '') {
			if(!checkEmailaddress($(this).val())) {
				alert(errMsg);
				mayReturn = false;
				$(this).removeClass('error').addClass('error');
				$(this).focus();
			}
		}
	});
	if(mayReturn){
		return true;
	} else {
		return false;
	}
}

/**
 * Show students total absence for a given period
 * 
 * @param errMsg The message to display when something goes wrong
 */
function showTotal(errMsg, form){
	var totForm = document.forms[form];
	if(checkDate(totForm.__date_from.value) && checkDate(totForm.__date_till.value)){
		totForm.submit();
	} else {
		alert(errMsg);
	}	
}


function toggleCourse(vak, vakregel, object) {
	var placeholder = $(vakregel).next(0);
	if(placeholder.is(':visible')) {
		flipRecord(vakregel);
	} else {
		if(!placeholder.hasClass('loaded')){
			placeholder.html('<div style="width:100%; text-align:center;"><img src="/fs/SOMTools/images/ajax-loader.gif" alt="Loading..." title="Loading..." /></div>');
			flipRecord(vakregel);
			var now = new Date();
			var ticks = now.getTime();
			placeholder.load('?wis_ajax&ajax_object='+object+'&vak='+vak+'&'+ticks, "", 
				function(responseText, textStatus, XMLHttpRequest) {
					if(textStatus == 'error') {
						placeholder.html('<p>Er is een fout opgetreden met het ophalen van de gegevens.</p>');
					} else if(textStatus == 'success' || textStatus == 'notmodified') {
						placeholder.addClass('loaded');
					}
				}
			);
		} else {
			flipRecord(vakregel);
		}
	}
}

function savePrivacy(object, verzorgerNummer, toestemming) {
	$.ajax({
		type: "POST",
		url: '?wis_ajax&ajax_object='+object+'&savePrivacy',
		data: {
			"verzorgerNummer": verzorgerNummer,
			"toestemming": toestemming
		},
		cache: false,
		success: function(data) {
			
		},
		error: function(jqXHR) {
			alert('mislukt');
		}
	});
}

/**
 * Expand/collapse a record in an overview
 * 
 * @param record The record to expand/collapse
 */
function flipRecord(record) {
	$(record).next(0).slideToggle('0.3');
	$(record).prev(0).toggleClass('overview__indicator_collapsed overview__indicator_expanded');
}

function flipRecord1(record, indicator) {
	$(record).slideToggle('0.3');
	$(indicator).toggleClass('overview__indicator_collapsed overview__indicator_expanded');
}

function flipStudies(record) {
	if($(record).parents('tr')) {
		if($(record).parents('tr').first().next(0).find('.studies').is(':visible')){
			$(record).parents('tr').first().next(0).find('.studies').slideUp('normal');
			$(record).className = 'studyIcon';	
		} else {
			$(record).parents('tr').first().next(0).find('.studies').slideDown('normal');
			$(record).className = 'studyIcon_active';	
		}
	}
}

/**
 * Expand all records for an overview
 * 
 * @param overview The overview to expand records for
 * @param elm_type Element (by tagName) to collect
 */
function expandAllRecords() {
	var overviewRecords = $('div.slide_div');
	overviewRecords.each(function(record){
		$(this).show();
		$(this).parent('li').children().first().removeClass('overview__indicator_collapsed overview__indicator_expanded');
		$(this).parent('li').children().first().addClass('overview__indicator_expanded');
	});
}

/**
 * Collapse all records for an overview
 * 
 * @param overview The overview to collapse records for
 * @param elm_type Element (by tagName) to collect
 */
function collapseAllRecords() {
	var overviewRecords = $('div.slide_div');
	overviewRecords.each(function(record){
		$(this).hide();
		$(this).parent('li').children().first().removeClass('overview__indicator_collapsed overview__indicator_expanded');
		$(this).parent('li').children().first().addClass('overview__indicator_collapsed');
	});
}

/**
 * Print portlet content
 */
function printOverview(portlet) {
	var printHeader = $.trim($('span.layout__titletext', portlet).first().html());
	var portletContent = $('div.layout__body', portlet).first().html();
	var popupWin = window.open("", "newwin");
	
	// Add title
	popupWin.document.write('<html><head><title>'+printHeader+' - Printversie</title>');
	
	// Add stylesheets
	$('link').each(function(stylesheet){
		popupWin.document.write('<link href="'+this.href+'" rel="stylesheet" type="text/css" media="'+this.media+'"/>');
	});
	/*$('script[src]').each(function(script){
		popupWin.document.write('<script src="'+this.src+'" type="text/javascript"></script>');
	});*/
	//popupWin.document.write('<script src="/fs/jquery/jquery-1.4.js" type="text/javascript"></script>');
	//popupWin.document.write('<script src="/fs/Atvo3Portlets/js/portlet_scripts_jquery.js" type="text/javascript"></script>');
	popupWin.document.write('<style>.result__overview {overflow: visible;}</style></head>');
	
	// Add body and content
	popupWin.document.write('<body style=\'background:none;\'>'+portletContent+'<script type=text/javascript>document.getElementById(\'result__overview\').style.width=\'100%\';</script></body></html>');
	popupWin.document.close();
	
}

/**
 * Onload do something ...
 */
$(function() {
	
	$('tr.slideTrigger').live('click', function () {
		$(this).next('tr').children('td').children('span').slideToggle('0.3');
		$(this).children('td').children('div').toggleClass('overview__indicator_collapsed overview__indicator_expanded');
	});
	
	$('a.result__figure > span').tooltip();
	$('a.staffmember__info').tooltip();
	$('a.department__info').tooltip();
	
	$('.dateInput').datepicker({ dateFormat: 'dd/mm/yy' });
	
	jQuery('.triggerBubble', jQuery('.result__table tbody tr td')).live("click", function(){
		var time = 250;
		var $triggerBubble = jQuery(this);
		var $bubble = jQuery('.bubble', $triggerBubble);
		//check if already open
		if($bubble.hasClass('open')) {
			$bubble.animate({
				opacity: 0
			}, time, 'swing', function() {
				$bubble.css('display', 'none');
				$bubble.removeClass('open');
				jQuery('img.openIcon',$triggerBubble).attr('src', '/fs/SOMTools/images/mini_right.png');
			});
		} else {
			jQuery('img.openIcon',$triggerBubble).attr('src', '/fs/SOMTools/images/mini_left.png');
			$bubble.css({
				display: 'inline'
			}).animate({
				opacity: 1
			}, time, 'swing', function() {
				$bubble.addClass('open');
			});
		}
		return false;
	});
	
	
	// For each widget, keep a data object containing a mapping of url-to-container for caching purposes.
	$('.objectWrapper').each(function(){
		$(this).data( 'bbq', {
			cache: {
				// If url is '' (no fragment), display this div's content.
				'': $(this).find('.bbq-current')
			}
		});
	});

	// For all links inside a widget, push the appropriate state onto the history when clicked.
	$('.objectWrapper a.ajax').live( 'click', function(e){
		var state = {},
  
		// Get the id of this widget.
		id = $(this).closest( '.objectWrapper' ).attr( 'id' ),
		
		// Get the url from the link's href attribute, stripping any leading #.
		url = $(this).attr( 'href' ).replace( /^.*\?/, '' );
		
		// Set the state!
		state[ id ] = url;
		$.bbq.pushState( state );

		// And finally, prevent the default link click behavior by returning false.
		return false;
	});
	
	// For all forms inside a widget, push the appropriate state onto the history when clicked.
	$('.objectWrapper form[method=post].ajax').live( 'submit', function(e){
		var state = {},
		
		that = $(this).closest( '.objectWrapper' ),
		// Get the id of this widget.
		id = that.attr( 'id' ),
		
		// Get the url from the link's action attribute, stripping any leading #.
		url = $(this).attr( 'action' ).replace( /^.*\?/, '' );
		
		// Set the state!
		state[ id ] = url;
		
		that.find( '.loader' ).show();
		
		rel = that.attr( 'rel' );
		$.post('?wis_ajax&ajax_object='+rel+'&'+ url, $('input[type=text],input[type=hidden],input[type=password],input[type=checkbox]:checked,input[type=radio]',this),
				function(data) {
					that.find( '.loader' ).hide();
					that.html(data);
				});

		// And finally, prevent the default link click behavior by returning false.
		return false;
	});

	
	// Bind an event to window.onhashchange that, when the history state changes, iterates over all widgets, getting their appropriate url from the
	// current state. If that widget's url has changed, display either our cached content or fetch new content to be displayed.
	$(window).bind( 'hashchange', function(e) {
  
		// Iterate over all widgets.
		$('.objectWrapper').each(function(){
			var that = $(this),

			// Get the stored data for this widget.
			data = that.data( 'bbq' ),

			// Get the url for this widget from the hash, based on the appropriate id property. 
			url = e.getState( that.attr( 'id' ) ) || '';
					
			if(url != '') {
				// If the url hasn't changed, do nothing and skip to the next widget.
				if ( data.url === url ) { return; }
				
				if(that[0].timer !== undefined){
					clearTimeout( that[0].timer );
					if(that[0].xhr !== undefined){
						that[0].xhr.abort();
					}
				}

				// Store the url for the next time around.
				data.url = url;

				// Remove .bbq-current class from any previously "current" link(s).
				that.find( 'a.active' ).removeClass( 'active' );

				// Hide any visible ajax content.
				that.find( '.bbq-content' ).children( ':visible' ).hide();

				// Add .bbq-current class to "current" nav link(s), only if url isn't empty.
				url && that.find( 'a[href="#' + url + '"]' ).addClass( 'active' );
				
				// Show "loader" content while AJAX content loads.
				that.find( '.loader' ).show();

				// Load external content via AJAX. 
				that.load('?wis_ajax&ajax_object='+that.attr('rel')+'&'+url, "", function() {
					that.find( '.loader' ).hide();
				});
			}
		});
	})
  
	// Since the event is only triggered when the hash changes, we need to trigger the event now, to handle the hash the page may have loaded with.
	$(window).trigger( 'hashchange' );
	
});
