/***********************************************************
Scriptname: 	watabs.1.0.js
Dependencies: 	jquery.1.4.3
Version: 		1.0 live
Description:	Create tabs inline

Copyright: 		Webavance B.V. 2011
Legal: 			Any use of this script without Webavance B.V.
				express written consent is prohibited
************************************************************/
$(document).ready( function(){
	$.watabs();
});

(function($) {
	
	$.watabs = function() {
		
		$('[watabs]').find('a').live('click', function(e) {
			e.preventDefault();
			
			$(this).parent().addClass('active');
			$(this).parent().siblings().removeClass('active');
			
			var url = (!!!$(this).attr('href')) ? false : $(this).attr('href') ;
			var target = (!!!$(this).attr('rel')) ? false : $('' + $(this).attr('rel')) ;
			
			if (target==false) return;
			
			if (url===false || url.length<=1) { // no AJAX url is defined so it must be simply toggling views
				
				$(this).parents('[watabs]').find('a').each(function(i, trg){
					$('' + $(trg).attr('rel')).css({ display: 'none' });
				});
				
				target.css({ display: 'inline' });
				
			} else { // found an url so do an AJAX call
				
				target.children().remove();
				target.addClass('watabs_loading');
				
				$.ajax({
					url: url,
					cache: false,
					dataType: 'json',
					type: 'GET',
					DOMtarget: target,
					success: function(content) {
						$(this.DOMtarget).removeClass('watabs_loading');
						$(this.DOMtarget).html(content);
					},
					error: function() {
						console.log('Could not load');
					}
				});
			}
		});
		
		$('[watabs]').find('a').each( function(i, a){ // find toggle tabs and toggle to the first window
			var url = (!!!$(a).attr('href')) ? false : $(a).attr('href') ;
			var target = (!!!$(a).attr('rel')) ? false : $('' + $(a).attr('rel')) ;
			
			if ((url===false || url.length<=1) && target!==false) {
				if ($(a).parent().prev().length==0) { 
					$(a).parent().addClass('active');
				} else {
					target.css({ display: 'none' });
				}
			}
		});
		
		$('[watabs]').find('a:eq(0)').each( function(i, a){ // find ajax tabs and activate the first one
			var url = (!!!$(a).attr('href')) ? false : $(a).attr('href') ;
			var target = (!!!$(a).attr('rel')) ? false : $('' + $(a).attr('rel')) ;
			
			if ((url!==false || url.length>1) && target!==false) {
				$(a).click();
			}
		});
		
	};
	
})($);
