/**
 * tkid.js, version 0.1.9
 * Copyright (c) 2008 Eike Reifhardt - bsmo
 *
 * "tkid" is licprototype enced under: http://creativecommons.org/licenses/by-sa/3.0/
 */


/**
 * namespace
 */

tkid = {
	Version :'0.1',
	CodeName:'tkid'
};

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

/**
 * unused for now
 */
tkid.options={
	path: '/misc/js/', 
	cssPath: '/misc/css/mednet/',
	lang: 'nl'
};

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

/**
 * some usefull functions
 *
 * @version 0.7
 */
tkid.tool = {
	
	// tests a number 
	isNegative: function(number) {
		return (number < 0) ? true : false;
	},
	
	isInteger: function(number) {
		return (number.toString().search(/^-?[0-9]+$/) == 0);
	},
	
	// as the function name says - selfexplaining
	negativeToPositive: function(number) {
		return (this.isNegative(number)) ? number*(-1) : number;
	},
	
	// square a quantity
	toSquare: function(number) {
		return number*number;
	},
	
	addScript: function(str) {
		var e = document.createElement('script');
		e.type = "text/javascript";
		e.text = str;
		$$("html")[0].down('head').appendChild(e); 
	},
	
	// cookie function props to: http://www.quirksmode.org/js/cookies.html
	createCookie: function(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=/";
	},
	
	readCookie: function(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;
	},
	
	eraseCookie: function(name) {
		createCookie(name,"",-1);
	},
	
	isFF2: function() {
		var reFF2 = /Firefox\/2/i;
		return reFF2.match(navigator.userAgent);
	},	
	
	isFF3: function() {
		var reFF3 = /Firefox\/3/i;
		return reFF3.match(navigator.userAgent);
	},
	
	isIE6: function() {
		var reIE6 = /MSIE 6/i;
		return reIE6.match(navigator.userAgent);
	},
	
	isIE7: function() {
		var reIE7 = /MSIE 7/i;
		return reIE7.match(navigator.userAgent);
	}	
};



/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

/**
 * Carousel
 *
 * inspired by prototype UI
 *
 * @todo: add ajax ability
 * @param int id
 * @param object optional for scriptaculous
 * @return bool false if somethign went wrong.
 * @version 1.0
 */
tkid.Carousel = Class.create(tkid, {
	
	// intern params only
	params:
	{
		'url'				: null,			// for ajax only
		'autoStart'			: false,		// auto scrol
		'axis'				: 'x',			// horrizontal(x) or vertical(y) carousel
		'class'				: 'karuseru',	// id of main wrapper
		'classPrevious'		: 'previous',	// suffix 
		'classNext'			: 'next',		// suffix
		'suffixOver'		: '_over'		// suffix
	},

	// scriptaculous only params
	options: {
		'duration'			: 0.2			// option parameter for scriptaculous fx
	},

	initialize: function(id) {
		
		if($(id)==null) return;
		
		// If there is an argument and it is an object, clone it to our obj.
		if(($A(arguments).length>1) && (typeof $A(arguments) == 'object')) {
			this.options = Object.clone($A(arguments)[1]);
		}

		
		var initUI = function(id) {

			if(typeof $(id) == 'object') {
				this.id=id; 			// id of container
				this.axis 				= ($(id).className.match('vertical')) ? 'y' : 'x';
				this.wrapper			= $(id).down('.wrap');
				this.container			= $(id).down('.container');
				this.showPager			= (this.count()<=1) ? false : true;
				
				// generate some html - still buggy in IE8 (beta)
				$(id).insert({top: new Element('div', {'className':'boxhead'})});
				
				if(this.showPager){
					$(id).down('.boxhead').insert({top: new Element('dl')});
					$(id).down('.boxhead dl').insert({bottom: new Element('dd', {'className':'previous'})});
					$(id).down('.boxhead dl').insert({bottom: new Element('dd', {'className':'next'})});
					$(id).down().insert({top: new Element('div', {'className':'pager'}).update('&nbsp;')});
				}
					
				this.previousButton 	= $(id).down('.previous');
				this.nextButton 		= $(id).down('.next');
				this.width				= this.wrapper.getWidth();
				this.height				= this.wrapper.getHeight();
				this.offset				= this.container.positionedOffset();
				this.itemsTotal			= this.count();
				
				// if there are no items, theres no need to run this script any further
				if(this.itemsTotal==0) {
					return false;
				}
				
				this.itemWidth 			= $(this.container).down('li').getWidth();
				this.itemHeight			= $(this.container).down('li').getHeight();
				this.itemsWidth			= this.container.down('li').getWidth() * this.itemsTotal;
				this.itemsHeight		= this.container.down('li').getHeight() * this.itemsTotal;
				this.itemsDisplayed 	= (this.axis == 'x') ? this.wrapper.getWidth()/this.itemWidth : this.wrapper.getHeight()/this.itemHeight; 
				
				// shaklack
				if(this.showPager){
					this.xFromY				= $(id).down('.pager');
				}
						
				if(this.itemsDisplayed==1) {
					if(this.showPager){
						tkid.options.pagerCount = this.itemsDisplayed;
						$(this.xFromY).update('['+this.itemsDisplayed + ' van ' + this.itemsTotal+']');
					}
				} 
				// console.log(this);
				return true;
			}
		}.bind(this);

		if(!initUI(id)) return false;
		
		// clone items
		var toKlone = $(id).down('ul').select('li');
		if((this.itemsDisplayed == this.itemsTotal) || tkid.tool.isInteger(this.itemsDisplayed/this.itemsTotal)) {
			// clone none - no carousel here
		} else {
			for(i=0;this.itemsDisplayed>i;i++) {
				for(j=0;toKlone.length>j;j++) {
					var myKlone = toKlone[j].cloneNode(true);
					var cyClone = this.container.down('ul').insert({'bottom':myKlone});
				}
			}
		}
		
		
		
		// private wrapper for button events
		var buttonEvent = function(event) {
			// assign methods to buttons, depending on event
			switch(event.type) {
				case 'mouseover':
					var clsName = event.target.className+''+this.params.suffixOver;
					event.target.className=clsName;
				break;
				case 'mouseout':
					var substringValue = event.target.className.length-this.params.suffixOver.length;
					event.target.className=event.target.className.substring(0, substringValue);
				break;
				case 'click':
					var scrollDirection = (event.target.className==this.previousButton.className) ? '-' : '+';						
					this.scroll( scrollDirection );
				break;
			};
		}.bind(this);

		if(this.showPager){
			// bind events to buttons
			['click','mouseover','mouseout'].each(function(event) {
				Event.observe(this.previousButton, 	event, 	buttonEvent.bindAsEventListener(this));
				Event.observe(this.nextButton, 		event,  buttonEvent.bindAsEventListener(this));
			}.bind(this));
		}
		return this;
	},
	
	// scrolls to the left or right and or top or bottom
	scroll: function(direction) {
		var that = this;
		
		if(this.axis == 'x') {
			var left		= this.container.positionedOffset().left;
			var width		= this.width;
		} else {
			var top			= this.container.positionedOffset().top;
			var height		= this.height;
		}

		var itemsDisplayed 	= (this.axis == 'x') ? this.wrapper.getWidth()/$(this.container).down('li').getWidth()
												 : this.wrapper.getHeight()/$(this.container).down('li').getHeight();
		var itemsCurrent 	= (this.axis == 'x') ? (this.container.down('li').getWidth() * this.itemsTotal) / $(this.container).down('li').getWidth()
												 : (this.container.down('li').getHeight() * this.itemsTotal) / $(this.container).down('li').getHeight();
		
		// private scope:
		var viewNext = function() {
			// [in]crement pager
			/* ------------------------------------------------------------------------------ */

			if(this.showPager){
				_pagerHTML = $(this.xFromY).innerHTML.split(' ');
				_pagerStart = _pagerHTML.first().substr(1,2);
				_pagerStart = parseInt(_pagerStart);
				
				if(_pagerStart==this.itemsTotal) {
					tkid.options.pagerCount=1;
				} else {
					tkid.options.pagerCount=(_pagerStart+1);
				}
				$(this.xFromY).update('['+tkid.options.pagerCount + ' van ' + this.itemsTotal+']');
			}

			/* ------------------------------------------------------------------------------ */
			
			if(this.axis == 'x') {
				var start = (this.count() * this.itemWidth) - (this.itemsTotal * this.itemWidth);
				if(tkid.tool.negativeToPositive(left) == start) {
					this.container.style.left = "0px";
					return "-"+(this.itemsDisplayed * this.itemWidth);
				}
				return left - width;
			} else {
				var start = (this.count() * this.itemHeight) - (this.itemsTotal * this.itemHeight);
				if(tkid.tool.negativeToPositive(top) == start) {
					this.container.style.top = "0px";
					return "-"+(this.itemsDisplayed * this.itemHeight);
				}
				return top - height;
			}
		}.bind(this);

		var viewPrevious = function() {
			// [de]crement pager
			if(this.showPager) {
				_pagerHTML = $(this.xFromY).innerHTML.split(' ');
				_pagerStart = _pagerHTML.first().substr(1,2);
				_pagerStart = parseInt(_pagerStart);
				
				if(tkid.options.pagerCount==1) {
					tkid.options.pagerCount=this.itemsTotal;
				} else {
					if((_pagerStart-1)==0) {
						tkid.options.pagerCount=this.itemsTotal;
					} else {
						tkid.options.pagerCount=(_pagerStart-1);
					}
				}
				$(this.xFromY).update('['+tkid.options.pagerCount + ' van ' + this.itemsTotal+']');
			}

			if(this.axis == 'x') {
				if(left==0) {
					var start = (this.count() * this.itemWidth) - (this.itemsTotal * this.itemWidth);
					this.container.style.left = "-"+start+"px";
					var toScrollExtra = start-(this.itemWidth*this.itemsDisplayed);
					return "-"+toScrollExtra;
				}
				return left + width;
			} else {
				if(top==0) {
					var start = (this.count() * this.itemHeight) - (this.itemsTotal * this.itemHeight);
					this.container.style.top = "-"+start+"px";
					var toScrollExtra = start-(this.itemHeight*this.itemsDisplayed);
					return "-"+toScrollExtra;
				}
				return top + height;
			}
		}.bind(this);

		// wrapper for private methods above
		this.toScroll = ('+'==direction) ? viewNext() : viewPrevious();
		
		var scrolDirection = (this.axis=='x') ? 'left' : 'top';
	
		var _beforeStart = function(that) {
			that.previousButton.up().hide();
		}.bind(this);
		
		var _afterFinish = function(that) {
			that.previousButton.up().show();
		}.bind(this);

		this.options = {
			duration: 0.2,
			transition: Effect.Transitions.linear,
			from: 0, 
			to: 1, 
			scope: 'scope', 
			limit: 1,
			queue:{ position: 'end', scope: 'scope', limit: 1 }
		};
		// {duration: 0.2, transition: Effect.Transitions.linear, from: 0, to: 1, scope: 'scope', limit: 1}
		var fxScrol = this.container.morph(scrolDirection+": "+this.toScroll+"px", 
		this.options, {
			beforeStart:_beforeStart(that),
			afterFinish:_afterFinish(that)
		});
		
		return;
	},
	
	// counts items 
	count: function() {
		return $(this.container).down('ul').childElements().length;
	},
	
	// some math
	getCommonDivisor: function(numerator, divisor) {
		if(numerator%divisor==0) return numerator;
		for(i=1;divisor>i;i++) {
			numerator++;
			if(numerator%divisor==0) {
				return numerator++;
			}
		}
		return;
	}
	
});

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

/**
 * this is a helper method which works only for a carousel tab
 *
 * @param string id 
 * @param string toShow
 * @version 0.5
 */
tkid.carouselTab = Class.create(tkid, {
	initialize: function(id, toShow) {
		
		this.id 		= id;
		this.container 	= $(this.id);
		this.headline 	= this.container.down('h2');	
		
		var tabIds 		= '';
		var i			= 0;
		
		// create basic elements
		this.headline.insert({after:new Element('div', {'className':'tabsCnt carousel'})});
		this.headline.insert({after:new Element('div', {'className':'tabsNav'})});

		$$('#'+this.id+' ul').each(
			function(c) {
				tabIds = (tabIds.length==0) ? c.id : (tabIds+' '+c.id);
			}
		);
		tabIds = $w(tabIds);


		this.container.childElements().each(function(e) {
		
			// create tab structure - works nicely
			if(e.tagName.toUpperCase() == 'STRONG') {
				this.headline.next('.tabsNav').insert(
					{bottom:new Element('a', {
						'href':'javascript:tkid.carouselTab.showTab(\''+id+'\', \'' + tabIds[i] + '\', \''+this.id+'tab-'+i + '\');', 
						'id':this.id+'tab-'+i
					}).update(e)}
				);
				i++;
			}
			
			// create carousel structure
			if(e.tagName.toUpperCase() == 'UL') {
				// alert('element is UL: ' + e.id);
				
				this.container.down('.tabsCnt').insert(
					{bottom: new Element('div', {'id':e.id})}
				);
				$(e.id).insert(
					{top:new Element('div', {'className':'wrap'})}
				);
				$(e.id).down('.wrap').insert(
					{top:new Element('div', {'className':'container'})}
				);
				$(e.id).down('.container').insert(
					{top:e.cloneNode(true)}
				);

				$(id).childElements().each(
					function(ce) {
						if(ce.nodeName.toUpperCase()=='UL') {
							ce.remove();
						}
					}
				);
				$(id).down('.tabsCnt').childElements().each(
					function(t) {
						t.down('ul').removeAttribute('id');
					}
				);
				
				
				if($(e.id).hasAttribute('class')) {
					// alert('has Class Name');
					$(e.id).setAttribute('class', $(e.id).className);
				}

			}
		}.bind(this)); // end each()

		// hide and show tab content
		this.tabs = this.container.down('.tabsNav');
		this.cnt  = this.container.down('.tabsCnt');

		this.cnt.childElements().each(function(e){e.hide()});
		
		tkid.carouselTab.showTab(this.id, toShow);

		// register click handler for tabs
		var eventTabs = this.tabs.childElements();
		for(i=0;eventTabs.length>i;i++) {
			Event.observe(eventTabs[i], 'click', function(event) {
				if(!Prototype.Browser.IE) {
					event.currentTarget.className ='activeTab';
				} else {
					event.srcElement.up().className ='activeTab';
				}
			});
		}

		// mark active tab
		for(i=0;tabIds.length>i;i++){
			if(toShow == tabIds[i]) eventTabs[i].className = 'activeTab';
		}

		return;
	}
});

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

// singleton method for carousel tab ...
/**
 *  singleton method for carousel tab ...
 *
 * @param string container 
 * @param string id
 * @param string self
 * @version 0.5
 */
tkid.carouselTab.showTab = function(container, id, self) {

	$(container).down('.tabsCnt').childElements().each(
		function(e){	
			e.hide();
		}
	);
	$(id).show();

	if(tkid.tool.isIE6() || tkid.tool.isFF2()) {
		$(id).setStyle({'left':'0'});
	} else {
		$(id).down('.container').setStyle({'left':'0'});
	}
	
	$(container).down('.tabsNav').childElements().each(function(e){
		if(typeof self == 'string') {
			if(e.id != self) e.className = '';
		}
	});
	
	if(typeof $(id).down('.next') == 'undefined') new tkid.Carousel(id);
};

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

// regular tabs:
// @TODO: do not follow links - just show tabs
tkid.tab = Class.create(tkid, {

	initialize: function(containerId) {
		if( !$(containerId) ) {
			return "ELEMENT_NOT_FOUND: " + containerId;
		}
		// init vars
		this.tabs = $H({});
		this.links = [];
		this.active = '';
		
		this.tabs = $(containerId).select('li a');
		// get and mod links + check ids  
		this.tabs.each(
			function(e) {
				var linkArr = e.href.split("#");
				if(typeof linkArr[1] == 'string') {
					this.links.push(linkArr[1]);
					e.href='#'+linkArr[1];
					
					e.observe('click', function(d) 
					{
						$(containerId).select('li.active')[0].removeClassName('active');
						e.up().addClassName('active');
						this.links.each(
							function(e) {
								$(e).hide();
							}
						);
						$(linkArr[1]).show();
						d.preventDefault();
					}.bind(this));
					
				}
			}.bind(this)
		);
		
		// auto set active
		if(this.active.length == 0) {
			this.active = this.links[0];
			this.tabs[0].up().addClassName('active');
		}
		
		// hide all besides active tab
		this.links.each(
			function(e) {
				$(e).hide();
			}
		);

		// show only active link
		$(this.active).show();

		// console.log(this);
	}

});
// lazy method for tkid.tab - to initialize tabs by className - even though:
// there must be an ID for each tab-element
tkid.allTabs = Class.create(tkid, {

	initialize: function(classname) {
		$$('.'+classname).each(function(e) {
			elm = e.select('ul[id]');
			new tkid.tab(elm[0].id);
		});
	}
	
});



/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

tkid.popup = Class.create(tkid, {

	initialize: function(classname, features) {
		
		if(typeof features == 'object') {	
			_pairs = '';
			$H(features).each(function(e){
				_pairs = _pairs+e[0]+'='+e[1]+',';
			});
			var pairs = _pairs.replace(/,$/,'');
		}
		var _pWinCount = 0;
		$$('.'+classname).each(function(e) {
			if(e.tagName.toUpperCase() == 'A') {
				e.observe('click', function(elm) {
					popWin = window.open(e.href, 'poppd'+_pWinCount, '"'+pairs+'"');
					popWin.focus();
					elm.preventDefault();
				});
				_pWinCount++;
			}
		});
		
	}
	
});

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */


tkid.Ajax = Class.create(tkid, {
	
	initialize: function(url) {
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				return transport.responseXML;
			},
			onFailure: function(transport) {
				return false;
			}
		});
	}
});

/**
 * shadowbox
 *
 * just a wrapper mothod to init and run the shadowbox - aka lightbox
 *
 * http://mjijackson.com/shadowbox/
 * Licence coasts: $20.00 USD
 * usage: new tkid.shadowbox();
 * @version 0.4
 */
tkid.shadowbox = Class.create(tkid, {

	initialize: function() {
	    var options = {
	        handleOversize:     'drag'
	    };
	    // console.log(Shadowbox);
	    if(typeof Shadowbox != "undefined") {
			Shadowbox.init(
				options
			);

	    }
	}
});


/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

// style switcher
tkid.changeStyle = Class.create(tkid, {
	initialize: function(styleName) {
		
		cookie = tkid.tool.readCookie('cookieMonstr');
		
		if((cookie == 'undefined') && (typeof styleName == 'undefined')) {
			return false;
		}
		
		if(cookie) {
			this.switchr(cookie);
		}
		
		if(typeof styleName != 'undefined') {
			tkid.tool.createCookie('cookieMonstr', styleName, 30);
			this.switchr(styleName);
		}

	},
	switchr: function(styleName) {
		$$('head link[rel]').each(function(e) {
			e.disabled = (e.title == styleName) ? false : true;
		});
	}
});

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

tkid.footerNav = Class.create(tkid, {
	initialize: function() {
		if($('navigatie') == null) return false;
		
		var myClone = $('navigatie').cloneNode(true);
		myClone.id='bodem_navigatie';
		var cyClone = $('navClone').insert({'bottom':myClone});
	}
});


/**
 * creates, modifies and changes stuff on the site. Works only for original and 
 * unchanged mednet template by bsmo!
 * @version 0.3
 */
tkid.buildBasics = Class.create(tkid, {
	initialize: function() {
		
			$$('ul li:first-child').each( function(e){ 
				e.addClassName('first')
			});
			$$('#content .three_colum_box div:first-child').each( 
				function(e){
					e.addClassName('first')
				}
			);
			$$('#content .prevpics img:first-child').each( 
				function(e){
					e.addClassName('first')
				}
			);
	
			$$('#sidebar .hilights_box .boxbody').each( function(e){
				Event.observe(e, 'mouseover' , function(){ 
					e.addClassName('hover')
				});
				Event.observe(e, 'mouseout' , function(){ 
					e.removeClassName('hover')
				});
			});
	
			
			if($('navigatie') != null) {
				var aItem = $("navigatie").down("li.active");
				$('navigatie').childElements().each( function(e){
					Event.observe(e, 'mouseover' , function(){
						$('navigatie').childElements().invoke('removeClassName', 'active');
						e.addClassName('active')
					});
					Event.observe(e, 'mouseout' , function(){
						e.removeClassName('active');
						if(aItem!=null){ aItem.addClassName("active"); }					
					});
				});
			}
			
			if(Prototype.Browser.WebKit) {
		    	$('emptyStyle').href= tkid.options.cssPath+'safari.css';
		    }
	
			// for article only
	    	if($('content')!=null){
				$('content').select('div.external_links').each( function(e){
					if(e.positionedOffset()[0]<300)	
						e.setStyle({width: '64em'});
				});
			}
			new tkid.externalURI();
			new tkid.shadowbox();
	}
});


/**
 * clearInput
 *
 * as the name states it - it clears the value of an input field - on focus
 *
 * @param string id
 * @version 0.1
 *
 * @TODO: Add Class Wrapper for it.
 */
tkid.clearInput = Class.create(tkid, {
	initialize: function(id) {
		Event.observe(id,	'focus', function(id){
			id.target.value = '';
		});
	}
});


/**
 * externalURI
 * 
 * grabs all links with a rel attribute and "external" as value and adds a target blank.
 * 
 * @version 0.1
 */
tkid.externalURI = Class.create(tkid, {
	initialize: function() {
		$$('a[rel=external]').each(
			function(elm) {
				elm.setAttribute('target', '_blank');
			}
		);
	}
});