$(document).ready(function(){

	// navigations bindings
	// ----------------------------------------------	
	$('#sidebartoggle_btn').click( function (){	// toggle sidebar + content
		toggleSidebar();	
	});
	$('#wrappertoggle_btn').click( function (){
		//wrapperToggle();
		closeContentWrapper();
		location.href = 'http://www.hgb-leipzig.de/systemdesign/#/';
	});
	$('#close_btn').hide().click(function () {
		closeContentWrapper();
	});
	$('#navigation div').click(function (){
		toggleTopicMenu( $(this) );
	});
	$('#hgb_link').css('cursor', 'wait');
	$('#sidebar #header h1 a').each( function(){
		
		$(this).attr('old_href', $(this).attr('href') ).attr('href', '#/');
		$(this).css('cursor', 'pointer');
		$(this).click( function(){
			//return false;
		});
		
	});
	
	
	// click on kiste_overlay blendet sidebar aus
	// ----------------------------------------------
	$('#kiste_overlay').click( function(){		
		//$(this).hide();		
		//wrapperToggle();		
	});		
	
	
	// ajax navigation
	// ----------------------------------------------	
	$('#navigation ul li a, #navigation #blog_btn a, #sidebar #imprint_link').each( function(){ // make ajax-links in the navi
	
		makeAjaxLinks( $(this) );
	
	});	
	window.setInterval(function() {

		current_url = location.href;	
		
		if (current_url != current_href){
			loadContent( current_url );		
			current_href = current_url;
		}
		
	}, 100); 
	
	
	
	// lade systemdesign welt
	// ----------------------------------------------	
	var world = 'systemdesign'
		 
	// load world 
	///*
	$('#kiste').load('kiste/systemdesign_template.php?w=' + world + '&options[fill_folders]=1&options[hide_boxoverlay]=1&options[lazy_load]=1' , function(){	

		// remove loading class
		setTimeout( "$('#world_container_wrapper').removeClass('loading')" , 1000 );

		// place google calender
		//$('#world_container').append('<iframe style="position:absolute; left:4078px; top: 61px;" src="restylegc/restylegc.php?src=p87fjed8qr5k09cghrhl7q119c%40group.calendar.google.com&showPrint=0&showTitle=0&showCalendars=0" style="border: 0" width="900" height="700" frameborder="0" scrolling="no"></iframe>');
		$('#world_container').append('<iframe style="position:absolute; left:4078px; top: 61px;" src="https://www.google.com/calendar/embed?src=p87fjed8qr5k09cghrhl7q119c@group.calendar.google.com&showPrint=0&showTitle=0&showCalendars=0&gsessionid=OK" style="border: 0" width="900" height="700" frameborder="0" scrolling="no"></iframe>');

		// mache flash windows transparent (nur fü windows wichtig, beim mac geht so)
		$('#world_container embed').attr('wmode', 'transparent');
		$('#world_container object')
			.prepend('<param name="wmode" value="transparent"> ')
			.css('display', 'none')						
		setTimeout("$('#world_container object').show()", 500);

	});	
	//*/

});

var current_url;
var current_href;
var html_real_root = 'http://www.hgb-leipzig.de/systemdesign/'
var html_ajax_root = 'http://www.hgb-leipzig.de/systemdesign/#/'

function makeAjaxLinks( link ){

	var this_href	= $(link).attr('href');
	var url_path	= parseUri(this_href); url_path = url_path.path;
	var url_querys	= parseUri(this_href); url_querys = url_querys.query;
	var url_anchors = parseUri(this_href); url_anchors = url_anchors.anchor;			
	
	var ajax_href =  '#/?' + url_querys;
	if(url_anchors){ ajax_href = ajax_href + '#' + url_anchors };				
	
	$(link).attr('old_href', this_href).attr('href', ajax_href);

}

function wrapperToggle(){
	
	var view = $('#sd_wrap').attr('view');
	
	if (view == 'open'){
		$('#sidebar').css('z-index', '1010');
		$('#content_wrapper').animate({left: -330}, 300, function (){
			$('#sidebar').css('z-index', '1002').animate({left: -240}, 150);
			$('#content_wrapper').animate({left: -544}, 150);
			
			///*
			// für die präsentation auskommentiert
			$('#content_wrapper').bind('mouseenter', function(){	
				
				$(this).attr('mouseenter', 'true');
				//$('#content_wrapper').animate({left: -534}, 150);
				
				setTimeout( function(){				
					if( $('#content_wrapper').attr('mouseenter') == 'xxxxtrue' ){
						//wrapperToggle();				
					}
				}, 2000);
				//wrapperToggle();
				
				$('#content_wrapper').unbind('mouseenter');
				
			});				
			//*/
			
		});			
		$('#kiste_overlay').hide();
		$('#wrappertoggle_btn').html('&raquo;');
		$('#sd_wrap').attr('view', 'closed');
	
	}else if (view == 'closed' || !view){
		$('#kiste_overlay').fadeIn('fast');
		$('#content_wrapper').animate({left: -330}, 150);
		$('#sidebar').css('z-index', '1010');
		$('#sidebar').animate({left: 0}, 150, function (){
			$('#content_wrapper').animate({left: 222}, 300, function (){
				$('#sidebar').css('z-index', '1002');			
			});			
		});
		$('#wrappertoggle_btn').html('&laquo;');					
		$('#sd_wrap').attr('view', 'open');	
	}
}
function setActiveArticel( li ){

	$('#navigation ul li.active').removeClass('active');
	
	if(li){
		$(li).addClass('active'); 	// mark red
		$(li).parent('ul').show();	// show its parent-container
	}

}
function toggleTopicMenu( topic ){
	
	var speed = 150;
	var view_state = $(topic).attr('view'); 
	if(view_state == 'open'){
		$(topic).attr('view', 'closed')
		$(topic).next('ul').slideUp(speed);
	}else if(view_state == 'closed' || !view_state){
		$(topic).attr('view', 'open');
		$(topic).next('ul').slideDown(speed);
	}
	
}
function toggleSidebar(){
	
	if( $('#sidebar').attr('view') == 'open'){

		$('#sidebar').animate({left: -215}, 200, function (){		
			
			///*
			// für die präsentation auskommentiert
			$('#sidebar #content_shadow').unbind('mouseenter').bind('mouseenter', function(){	
				//alert('2');
				
				$('#sidebar #content_shadow').unbind('mouseenter');
				toggleSidebar();
				
				$('#sidebar').unbind('mouseleave').bind('mouseleave', function(){					
					toggleSidebar();					
				});
				$('#sidebar').bind('mousedown', function(){ 
					$('#sidebar').unbind('mouseleave');
				});
			});		
			//*/
			
		});
		$('#sidebartoggle_btn').html('&raquo;');
		$('#sidebar').attr('view', 'closed');
		
		
	
	}else if( $('#sidebar').attr('view') == 'closed'){
	
		$('#sidebar').animate({left: 0}, 200, function(){
			$('#sidebar').attr('view', 'open');	
			$('#sidebartoggle_btn').html('&laquo;');
		});
		
		
		
	
	
	}

}
function openContentWrapper(){

	if( $('#content_wrapper').attr('view') != 'open' ){
	
		$('#sd_wrap').attr('view', 'open');
		$('#content_wrapper').show();
		$('#content_wrapper').css('z-index', '');
		$('#content_wrapper').css('left', '');
		$('#content_wrapper').animate({left: 222}, 400, function (){
			$('#content_wrapper').css('z-index', '1002');
			$('#content_wrapper').attr('view', 'open');;
		});
	
		$('#sidebartoggle_btn').hide();
		
		return 'open';
		
	}else{
	
		return false;
	
	}

}
function closeContentWrapper(){

	setActiveArticel();
	
	$('#content_wrapper').css('z-index', '');
	$('#content_wrapper').animate({left: -570}, 300, function (){
		//$('#sidebar').css('z-index', '1002').animate({left: -240}, 150);
		//$('#content_wrapper').animate({left: -550}, 150);
	});
	$('#content_wrapper').attr('view', 'closed');
	$('#kiste_overlay').hide();
	
	$('#sidebartoggle_btn').show();

}

function loadContent( url ){	

	// safari needs this replacement
	var url = url.replace(/%23/g, "#")

	var real_url 	= url.replace(/#\//g, "");
	var url_path	= parseUri(real_url); url_path = url_path.path;
	var url_querys	= parseUri(real_url); url_querys = url_querys.query;
	var url_anchors = parseUri(real_url); url_anchors = url_anchors.anchor;			
	
	// break: wenn url == html_real_root oder html_ajax_root
	if(url == html_real_root || url == html_ajax_root){
	
		closeContentWrapper();		
		return false;
	
	}
	
	// mark the link in navi
	setActiveArticel( $('#navigation ul li a[old_href='+real_url+']').parent('li') );

	//
	
	// wenn anker der bereits geladen ist
	if( url_anchors && $('.'+url_anchors).size() ){
	
		if ( openContentWrapper() ){
			$('#archiv_wrap').scrollTo( '#'+url_anchors, 0, {offset: {top:-50, left:0}} );	// wenn der content container erst geöffnet werden musste
		}else{
			$('#archiv_wrap').scrollTo( '#'+url_anchors, 500, {offset: {top:-50, left:0}} );	
		}	
		
		return false;
	
	}
	
	$.ajax({
		//url: real_url,
		url: '?' + url_querys, // die übergabe von ankern verursacht übelst probleme
		cache: true,
		type: 'POST',
		//dataType: 'html',
		success: function( data ){
			
			// füge geladenenen content ein und fade in
			$('#content')
				.html( data )
				.find('.post')
				.fadeIn(100);	
			
		},
		complete: function( ){
		
			// wenn ein blog eintrag aufgerufen wurde, wird blog in der nav markiert
			if( $('#content h3:contains("Blog")').size() ) {
				
				$('#blog_btn').addClass('active');
				
			}else{
				
				$('#blog_btn').removeClass('active');
				
			}			
			
			// wandle alle links auf den archivseiten in ajax-links um > '#/' 
			$('.archive #content .post:not(.category-blog,.category-theclass)').find('a').each( function(){
			
				makeAjaxLinks( $(this) );
			
			});
			
			// wandle paginierungslinks in ajax-links
			$('.nextprevious').find('a').each( function(){
			
				makeAjaxLinks( $(this) );
			
			});
			
			// wandle archive-links im content header in ajax-links um > '#/' 
			$('#content h3:first').find('a').each( function(){
			
				makeAjaxLinks( $(this) );
			
			});	
			
			// wandle blog-headlines in ajax-links um > '#/' 
			$('#content .category-blog h4').find('a').each( function(){
			
				makeAjaxLinks( $(this) );
			
			});
			
			// wandle more-links in ajax-links um > '#/' 
			$('#content a.more-link').each( function(){
			
				makeAjaxLinks( $(this) );
			
			});
			
			// entferne links zu attachment_ids
			// wandle links zu target="_blank" um
			$('.single #content .post, #content .post.category-blog .story').find('a:not(".more-link")').each( function(){			
				
				var this_href = '' + $(this).attr('href');
				var this_html = '' + $(this).html();
				if( this_href.search('attachment_id') > 0 && this_html.search('<img') > 0 ){
				
					//alert( this_href + ' , ' + this_html )
					
					$(this)
						//.after( $(this).html() ) // füge link-html nach dem link ein
						//.remove()	// entferne link
				
				}else{
				
					$(this).attr('target', '_blank');
				
				}
			
			});
			
			
			
			// ajax submit comment form
			$('form#commentform').submit(function() { 

				$(this).ajaxSubmit({
					//target:        '#respond',		// target element(s) to be updated with server response 
					success: function( response ){
						
						loadContent( location.href )
						$('body').css('cursor', '');
					
					},
					beforeSubmit:  function(){
					
						$('body').css('cursor', 'wait');
					
					},			
					//beforeSubmit:  showRequest, 		// pre-submit callback 
					//success:       showResponse			// post-submit callback 
			 
					// other available options: 
					//url:       url         // override for form's 'action' attribute 
					//type:      type        // 'get' or 'post', override for form's 'method' attribute 
					//dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
					//clearForm: true        // clear all form fields after successful submit 
					//resetForm: true        // reset the form after successful submit 
			 
					// $.ajax options can be used here too, for example: 
					//timeout:   3000 
				}); 

				// !!! Important !!! 
				// always return false to prevent standard browser submit and page navigation 
				return false; 
			}); 			
			
			
			// ladebalken ready
			$('#content hr')
				.stop()
				.css('width', '56px');				
			
			// wenn anker scrolle zu ihm
			if(url_anchors){
				
				$('.post').scrollTo( '#'+url_anchors, 500, {offset: {top:-50, left:0}} );
				$('#archiv_wrap').scrollTo( '#'+url_anchors, 500, {offset: {top:-50, left:0}} );
				
			// ansonsten wird nach jedem laden ganz nach oben gescrollt
			} else {	

				$('.post').scrollTop( 0 );
				
			}	
			
		},
		beforeSend: function( ){			
		
			$('#kiste_overlay').fadeIn('fast');
			openContentWrapper();
			$('#content').html('<h3>&nbsp;<img src="wordpress/wp-content/themes/systemdesign/layout/images/ajax-loader.gif" /><br /></h3><hr />');
			
			// ladebalken animation
			$('#content hr')
				.css('width', '1px')
				.animate({width: 56}, 1000);				
			
		}
	});
	
	$('#kiste_overlay').fadeIn('fast');
	
}	
// wenn die seite nicht mit einem gültigen ajax-link aufgerufen wird
// wird hier der zum ajax-link weitergeleitet
var onload_href = location.href;
if( onload_href.indexOf( html_ajax_root ) ){
	
	var new_href = str_replace( html_real_root , html_ajax_root , onload_href);	
	location.href = new_href;
	
}

/* --------------------------------------- */

function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
function parseUri(sourceUri){
   
	/* parseUri JS v0.1, by Steven Levithan (http://badassery.blogspot.com)
	Splits any well-formed URI into the following parts (all are optional):
	----------------------
	• source (since the exec() method returns backreference 0 [i.e., the entire match] as key 0, we might as well use it)
	• protocol (scheme)
	• authority (includes both the domain and port)
		• domain (part of the authority; can be an IP address)
		• port (part of the authority)
	• path (includes both the directory path and filename)
		• directoryPath (part of the path; supports directories with periods, and without a trailing backslash)
		• fileName (part of the path)
	• query (does not include the leading question mark)
	• anchor (fragment)
	*/

    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};
    
    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }
    
    // Always end directoryPath with a trailing backslash if a path was present in the source URI
    // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }
    
    return uri;
}
function getFileExtension(filename) {
	return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}




