jQuery.fn.getTotalWidth = function(){
	return 	jQuery(this).width() + 
			parseInt(jQuery(this).css('paddingRight')) + 
			parseInt(jQuery(this).css('paddingLeft')) + 
			parseInt(jQuery(this).css('borderRightWidth')) + 
			parseInt(jQuery(this).css('borderLeftWidth'))
			;
};

jQuery.fn.getTotalHeight = function(){
	
	// need to do this cause ie sets borderWidth default to "medium"
	borderTopWidth = parseInt(jQuery(this).css('borderTopWidth'));
	if(isNaN(borderTopWidth)) {
		borderTopWidth = 0;
	}
	borderBottomWidth = parseInt(jQuery(this).css('borderBottomWidth'));
	if(isNaN(borderBottomWidth)) {
		borderBottomWidth = 0;
	}
	
	return 	jQuery(this).height() + 
			parseInt(jQuery(this).css('paddingTop')) + 
			parseInt(jQuery(this).css('paddingBottom')) +
			borderTopWidth + 
			borderBottomWidth
			;
};

jQuery.fn.getUlHeight = function(){
	//console.time('getUlHeight') ;
	var heigth = 0;
	var ul = jQuery(this);
	
	content = ul.children('li').children('a');
	aHeight = 	content.getTotalHeight() + 
				parseInt(content.css('marginTop')) + 
				parseInt(content.css('marginBottom'));
	
	height = aHeight*content.length;
	//console.log(aHeight+'*'+content.length+'='+height);
	/*
	ul.children('li').children('a').each(function(){
		myself = jQuery(this);
		heigth += 	myself.getTotalHeight() + 
					parseInt(myself.css('marginTop')) + 
					parseInt(myself.css('marginBottom'));
		
	});*/
	//console.timeEnd('getUlHeight');
	return parseInt(height);
};

(function($){
	$.fn.pageBrowser = function(options) {
		
		var rootUL;
		var pageBrowser;
		//var window;
		var depthUL;
		var allUL;
		var allLI;
		var subUL;
		var parentUL;
		var currentLabel = false;
		
		var defaults = {
			
			width:0,
			height:300,
			
			startpageUid: 1,
			startpageDoktype: 1,
			starpageCacheHash: false,
			
			classPage: 'pageBrowserPage',
			classWindow: 'pageBrowserWindow',
			classLink: 'pageBrowserLink',
			classGotChild: 'pageBrowserGotChild',
			classBack: 'pageBrowserBack',
			classCurrent: 'pageBrowserCurrent',
			classRootline: 'pageBrowserRootline',
			classRootlineCurrent: 'pageBrowserRootlineCurrent',
			classRootlineFollow: 'pageBrowserRootlineFollow',
			classRootlineLabel: 'pageBrowserRootlineLabel',
			classContentElement: 'pageBrowserContentElement',
			classLastLi: 'pageBrowserLastLi',
			classAjaxLoading: 'pageBrowserAjaxLoading',
			
			labelBack: 'zur&uuml;ck',
			labelRootline: 'w&auml;hle aus:',
			labelAll: 'Alle',
			
			requestUri: '/?type=323',
				
			speed: 250,
			
			debug: false
		}
		
		var options = $.extend(defaults, options);  
		
		var loadStartpage = function(pageUid, pageDoktype, pageCacheHash) {
			
			initLi = rootUL.find('.pageBrowserAjaxInit');
			
			$.ajax({
				url: options.requestUri,
				data: {
					'tx_scmpagebrowser_pi1[pageUid]': pageUid,
					'tx_scmpagebrowser_pi1[pageDoktype]': pageDoktype,
					'cHash': pageCacheHash
				},
				cache: true,
				timeout: 5000,
				type: 'GET',
				dataType: 'json',
				beforeSend: function(XMLHttpRequest){
					//link.addClass(options.classAjaxLoading);
				},
				complete: function(XMLHttpRequest, textStatus){
					//link.removeClass(options.classAjaxLoading);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					if (options.debug === true) 
						console.log(XMLHttpRequest);
					if (options.debug === true) 
						console.log(textStatus);
					if (options.debug === true) 
						console.log(errorThrown);
				},
				success: function(json, textStatus, XMLHttpRequest){
					
					if($(json).length == 0) {
						return false;
					}
					
					var numRows = 0;
					$.each(json, function(i,row){
						numRows = i;
					});
	
					if(numRows == 0) return false;
					
					var startpageLIs = Array();
					startpageLIs = $(document.createElement('span'));
					
					$.each(json, function(i,row){
						
						newLI = jQuery(document.createElement('li'));
						newA = jQuery(document.createElement('a'));
	
						newA.attr('pid',row.pid);
						newA.attr('doktype',row.doktype);
						newA.attr('href',row.href);
						newA.attr('title',row.title);
						newA.attr('chash',row.chash);
						
						newA.html(row.title);
						
						newA.click(function(){
							if(options.debug === true) console.log('finished klick');
							clickEvent(this);
							return false;
						});
						
						newLI.append(newA);
						
						if(row.doktype == 1) {
							newLI.addClass(options.classGotChild);
						}

						if(numRows == i) {
							newLI.addClass(options.classLastLi);
						}
						
						startpageLIs.append(newLI);
					});

					rootUL.prepend(startpageLIs);
					
					refresh_allUL();
				}
			});
		};
		
		var clickEvent = function(link) {
			//console.log('test');

			link = jQuery(link);
			link.blur();
			var subUL = link.next();
			var parentUL = link.parents('ul:eq(0)');
			var pageUid = link.attr('pid');
			var pageDoktype = link.attr('doktype');
			var pageCacheHash = link.attr('chash');
			var pageHref = link.attr('href');
			
			//
			// fetch ajax content - if fetched then process content und scroll to slide
			//
			
			if(pageDoktype == 3) {
				window.location = '/'+pageHref;
				return false;
			}
			if(options.debug === true) console.log('start ajax');
			$.ajax({
				url: options.requestUri,
				data: {	'tx_scmpagebrowser_pi1[pageUid]': pageUid,
						'tx_scmpagebrowser_pi1[pageDoktype]': pageDoktype,
						'cHash': pageCacheHash
						},
				cache: true,
				timeout: 5000,
				type: 'GET',
				dataType: 'json', 
				beforeSend: function(XMLHttpRequest) {
					link.addClass(options.classAjaxLoading);
					if(options.debug === true) console.log('requesting data');
				},
				complete: function(XMLHttpRequest, textStatus){
					link.removeClass(options.classAjaxLoading);
					if(options.debug === true) console.log('ajax end');
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					if(options.debug === true) console.log(XMLHttpRequest);
					if(options.debug === true) console.log(textStatus);
					if(options.debug === true) console.log(errorThrown);
				},
				success: function(json, textStatus, XMLHttpRequest){
	   				
					if(options.debug === true) console.log('fetching data was a success ');
					
					if($(json).length == 0) {
						if(options.debug === true) console.log('no json data found');
						return false;
					}
					
					var numRows = 0;
					$.each(json, function(i,row){
						numRows = i;
					});
	
					if(numRows == 0) return false;
					
					//if(subUL.length > 0) subUL.remove();
					//return false;
					
					var subUL = document.createElement('ul');
					subUL = jQuery(subUL);
					subUL.addClass(options.classPage);
					
					$.each(json, function(i,row){
						
						var newLI = document.createElement('li');
						newLI = jQuery(newLI);
						
						var newA = document.createElement('a');
						newA = jQuery(newA);
	
						newA.attr('pid',row.pid);
						newA.attr('doktype',row.doktype);
						newA.attr('href',row.href);
						newA.attr('title',row.title);
						newA.attr('chash',row.chash);
						
						newA.html(row.title);
						
						newA.click(function(){
							if(options.debug === true) console.log('finished klick');
							clickEvent(this);
							return false;
						});
						
						newLI.append(newA);
	
						if(row.doktype == 1)
							newLI.addClass(options.classGotChild);
						if(numRows == i)
							newLI.addClass(options.classLastLi);
							
						subUL.append(newLI);
						
					});
					
					subUL.width(options.width);
					link.after(subUL);
					refresh_allUL();
					
					//
					// give current page the current-class
					//
					allUL.removeClass(options.classCurrent);
					subUL.addClass(options.classCurrent);
					
					//
					// get path-depth
					//
					depthUL = subUL.parents('ul').size();
					var pathId = 'pageBrowserPathNo'+depthUL;
					
					//
					// show backButton on demand
					//
					if(depthUL > 0) {
						buttonBackA.show();
					}
					
					if(currentLabel != false) {
						rootlineFollow.append('<span id="'+pathId+'">'+currentLabel+'</span>');
					}else{
						rootlineFollow.append('<span id="'+pathId+'">'+options.labelAll+'</span>');
					}
					
					rootlineCurrent.html(link.html());
					currentLabel = rootlineCurrent.html();
					
					//
					// show full height of parentUL and make subUL the max height for scrolling
					//
					parentUL.css({'overflow-x':'visible','overflow-y':'visible'});
					subUL.css({	left: options.width+'px',
								display: 'block',
								height:ulMaxHeight,
								'overflow-x' :'hidden',
								'overflow-y':'hidden'
								});
					
					//
					// do the animation and show the sub(next)slide
					//
					rootUL.animate({ left: '-='+options.width+'px' }, options.speed,false,function(){
						if(subUL.getUlHeight() > ulMaxHeight) {
							subUL.css({'overflow-x' :'hidden','overflow-y':'scroll'});
							subUL.scrollTop(0);
						}else{
							subUL.css({'overflow-x' :'hidden','overflow-y':'hidden'});
						}
					});
					
					//
					// programm the backbutton
					//
					jQuery(buttonBack).unbind('click');
					jQuery(buttonBack).click(function(){
							
						depthUL -= 1;
						if(depthUL >= 0) {
									
							subUL = rootUL.find('.'+options.classCurrent);
							
							parentUL = subUL.parents('ul:eq(0)');
							allUL.removeClass(options.classCurrent);
							parentUL.addClass(options.classCurrent);
	
							lastPage = rootlineFollow.find('span:last-child');
							rootlineCurrent.html(lastPage.html());
							currentLabel = lastPage.html();
							lastPage.remove();
							
							
							subUL.css({'overflow-x' :'hidden','overflow-y':'hidden'});	
							rootUL.animate({ left: '+='+options.width+'px' }, options.speed,false,function(){
								subUL.css({display:'none'});
								if(rootUL.height() > ulMaxHeight) {
									parentUL.css({'overflow-x' :'hidden','overflow-y':'scroll','height':ulMaxHeight});
									parentUL.scrollTop(0);
								}else{
									parentUL.css({'overflow-x' :'hidden','overflow-y':'hidden','height':ulMaxHeight});
								}
							});
	
						}
						
						//
						// hide back-button on demand
						//
						if(depthUL <= 0){
							currentLabel = false;
							rootlineCurrent.html(options.labelRootline);
							buttonBackA.hide();
						}
						return false;
					});// END BACK BUTTON ON CLICK
					
				}// END success FUNCTION
			});// END $.ajax(...)
			
			if(options.debug === true) console.log('finished klick');
			return false;
		};
		
		var refresh_allUL = function() {
			allUL = pageBrowser.find('ul');
		};
		
		//	main function
		return this.each(function() {
			
			//
			// initialize
			//
			pageBrowser = jQuery(this);
			if(defaults.width == 0) options.width = pageBrowser.width();
			if(defaults.height == 0) options.height = pageBrowser.height();
			
			rootUL = pageBrowser.children('ul').not('ul.'+options.classContentElement);
			rootChildrenUL = rootUL.find('ul');

			refresh_allUL();
			allLI = pageBrowser.find('li');
			
			if(defaults.width == 0) options.width = pageBrowser.width();
			if(defaults.height == 0) options.height = pageBrowser.height();
			
			//
			// create backButton
			//
			buttonBack = document.createElement('a');
			jQuery(buttonBack)	.attr('href','#')
								.addClass(options.classBack)
								.html(options.labelBack);
			pageBrowser.append(buttonBack);
			buttonBackA = pageBrowser.find('.'+options.classBack);
			buttonBackA.hide();
			
			//
			// create rootline
			//
			rootline = document.createElement('div');
			rootlineCurrent = document.createElement('span');
			rootlineFollow = document.createElement('span');
			rootlineFollow = jQuery(rootlineFollow);
			rootlineCurrent = jQuery(rootlineCurrent);
			rootlineCurrent.addClass(options.classRootlineCurrent).html(options.labelRootline);
			rootlineFollow.addClass(options.classRootlineFollow);
			jQuery(rootline)	.addClass(options.classRootline)
								.append(rootlineFollow)
								.append(rootlineCurrent);
			
			pageBrowser.prepend(rootline);
			rootlineDIV = pageBrowser.find('.'+options.classRootline);
			
			//
			// init sizes
			//
			if (buttonBackA.css('position') == 'absolute') {
				buttonBackHeight = 0;
			} else {
				buttonBackHeight = buttonBackA.getTotalHeight() + parseInt(buttonBackA.css('marginTop')) + parseInt(buttonBackA.css('marginBottom'));
			}
			rootlineHeight = rootlineDIV.getTotalHeight()+parseInt(rootlineDIV.css('marginTop'))+parseInt(rootlineDIV.css('marginBottom'));
			allULPaddingTB = parseInt(rootUL.css('paddingTop'))+parseInt(rootUL.css('paddingBottom'));
			allULPaddingLR = parseInt(rootUL.css('paddingLeft'))+parseInt(rootUL.css('paddingRight'));
			ulMaxHeight = options.height-allULPaddingTB-rootlineHeight-buttonBackHeight;
			
			allUL.height(ulMaxHeight);
			allUL.width(options.width);
			
			// 
			// add classnames to unorderd lists
			//
			allUL.each(function(i,el){
				
				jQuery(this)
						.css({	//width:options.width-jQuery(this).css('padding-left')-jQuery(this).css('padding-right'),
								//height:options.height-jQuery(this).css('padding-top')-jQuery(this).css('padding-bottom'),
								display:'none'
								})
						.addClass(options.classPage);
			});
			
			rootUL.css('display','block');
			
			//
			// make links usable
			//
			/*console.log(rootUL);
			rootUL.find('ul').find('a').each(function(i,el){
				
				jQuery(this).click(function(){ // ----- show the next menu
					
					if (jQuery(this).attr('pid') != 'undefined') {
						clickEvent(this);
					}else{
						jQuery(this).blur();
					}
					
					return false;
					
				});	// END 

			});*/
			loadStartpage(options.startpageUid,options.startpageDoktype,options.starpageCacheHash);
			pageBrowser.css('display', 'block');
		});
		
	};
})(jQuery);