
// History
(function(window,undefined){

	// Establish Variables
	var
		History = window.History,
		State = History.getState();

	// Log Initial State
	History.log('initial:', State.data, State.title, State.url);

	// Bind to State Change
	History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
		// Log the State
		var State = History.getState(); // Note: We are using History.getState() instead of event.state
		History.log('statechange:', State.data, State.title, State.url);
	});

	// Prepare Buttons
	var
		buttons = document.getElementById('buttons'),
		scripts = [
			'History.pushState({state:1,rand:Math.random()}, "State 1", "?state=1"); // logs {state:1,rand:"some random value"}, "State 1", "?state=1"',
			'History.pushState({state:2,rand:Math.random()}, "State 2", "?state=2"); // logs {state:2,rand:"some random value"}, "State 2", "?state=2"',
			'History.replaceState({state:3,rand:Math.random()}, "State 3", "?state=3"); // logs {state:3,rand:"some random value"}, "State 3", "?state=3"',
			'History.pushState(null, null, "?state=4"); // logs {}, "", "?state=4"',
			'History.back(); // logs {state:3}, "State 3", "?state=3"',
			'History.back(); // logs {state:1}, "State 1", "?state=1"',
			'History.back(); // logs {}, "The page you started at", "?"',
			'History.go(2); // logs {state:3}, "State 3", "?state=3"'
		],
		buttonsHTML = ''
		;


})(window);

// Vars zum highlighten der sub_navigation, werden in den tpl arbeiten und filter gesetzt
var filter;
var typ;
var texttyp;

// gallery clearscreen timer
var csStartTimer = true;

// History vars
var activeStateData;

$(document).ready(function() {
	$('#start-ajax-loader').css('display', 'none');
	activeStateData = {
		side:{id: $('.side_list').attr('id'), activeItem: $('.side_list > a.active').attr('pid')},
		main:{pid: $('.side_list > a.active').attr('pid'), page: $('.side_list > a.active').attr('page')}, 
		nav:{activeItem:$('.nav_item a.active').attr('id') , activeSubitem:$('.sub_item[active=true] > a.active').attr('rel')}
	};
	
	hosturl = hosturl.replace('http://www.haubitz-zoche.de', '');
		
	$.fn.isChildOf = function(exp){
	return $(this).parents().filter(exp).length>0;
	};
	
	jQuery.fn.dwFadingLinks = function(settings) {
	  settings = jQuery.extend({
	    color: '#ff8c00',
	    duration: 150
	  }, settings);
	  return this.each(function() {
		if(!$(this).isChildOf('#main_container') && !$(this).isChildOf("#qtranslate-chooser")) {
	    	var original = '#444';
	    	$(this).unbind('mouseover').bind('mouseover', function() { $(this).animate({ color: settings.color },settings.duration); });
	    	$(this).unbind('mouseout').bind('mouseout', function() { $(this).animate({ color: original },settings.duration); });
		}
	  });
	};
	
	// Link hover effect
	$('a').dwFadingLinks({
	    color: '#0a7098',
	    duration: 150
	  });
	
	$('li.lang-de a, li.lang-en a').unbind('mouseout');
	$('li.lang-de a, li.lang-en a').unbind('mouseover');
	
	// Handle sub_items visibility
	$('.sub_item[active="true"]').css('display', 'block');
	
	// Handle sub_items active links
	if(filter !== undefined) {
		$('.filter_tag[rel="'+filter+'"]').addClass('active');
	}
	
	if(typ !== undefined) {
		$('.work_type[rel="'+typ+'"]').addClass('active');
	}
	
	if(texttyp !== undefined) {
		$('.text_type[rel="'+texttyp+'"]').addClass('active');
	}
	
	// Show submenus
	$('.nav_item a').live('mouseenter',function(event) {
		$('.sub_item').css('display', 'none');
		$('.sub_item[rel="'+$(this).attr('rel') +'"]').css({'display': 'block', 'margin-left': $(this).parent().position().left - 190});
	});
	
	// Position submenus
	$('.nav_item a').each(function(index) {
		$('.sub_item[rel="'+$(this).attr('rel') +'"]').css('margin-left', $(this).parent().position().left - 190 - (index * 27));
	});
	
	// Hide submenus and show active submenu
	$('#navigation').mouseleave(function(event) {
		$('.sub_item').css('display', 'none');
		$('.sub_item[active="true"]').css('display', 'block');
	});
	
	
	// Hide texts of photoprojects
	
	$('.show_text').live('click', function(event) {
		$(this).next().fadeIn();
		return false;
	});
	
	// AJAX
	
	$('.ajaxlink').live('click', function(event) {
		var url = $(this).attr('href');
		url = url.replace('http://www.haubitz-zoche.de', '');
		
		// Continue as normal for cmd clicks etc
		if ( event.which == 2 || event.metaKey ) { return true; }
		
		if($(this).hasClass('active'))
			return false;
		
		if($(this).isChildOf('#side_navigation')) {
			History.pushState({
								side:{id: $(this).parent().attr('id'), activeItem: $(this).attr('pid')},
								main:{pid: $(this).attr('pid'), page: $(this).attr('page')}, 
								nav:{activeItem:activeStateData.nav.activeItem , activeSubitem:activeStateData.nav.activeSubitem}
							}, 
							null, url);

		} else if($(this).isChildOf('#sub_navigation')) {
			History.pushState({
								side:{id: '', activeItem: ''},
								main:{pid: '', page: ''}, 
								nav:{activeItem:$('.nav_item > a[rel='+ $(this).parent().attr('rel') +']').attr('id') , activeSubitem:$(this).attr('rel')}
							}, 
							null, url);
			
		} else if($(this).isChildOf('#navigation')) {
			History.pushState({
								side:{id: '', activeItem: ''},
								main:{pid: '', page: ''}, 
								nav:{activeItem:$(this).attr('id') , activeSubitem:$('.sub_item[rel='+ $(this).attr('rel') +'] a:first-child').attr('rel')}
							}, 
							null, url);
		} else if ($(this).hasClass('text_link')) {
			History.pushState({
								side:{id: 'none', activeItem: ''},
								main:{pid: $(this).attr('pid'), page: $(this).attr('page')}, 
								nav:{activeItem:activeStateData.nav.activeItem , activeSubitem:activeStateData.nav.activeSubitem}
							}, 
							null, url);
		} else if($(this).isChildOf('#text_back')) {
			History.pushState({
								side:{id: '', activeItem: ''},
								main:{pid: '', page: ''}, 
								nav:{activeItem:'nav_4' , activeSubitem:'bibliography'}
							}, 
							null, url);
		}
		

		event.preventDefault();
		return false;
	});
	
	// History onstatechange init
	initOnStateChangeHandler();
	
	// Click on gallery-image
	$('.image').live('click', function(event) {
		var img_div = $(this);
		
		if(isRightHalf(event.pageX, $(img_div).offset().left, $(img_div).attr('imgwidth')))
			nextImage(img_div);
		else
			prevImage(img_div);
		
		
	});
	
	// Click on gallery navigation
	$('#gallery_left').live('click', function(event) {
		prevImage($('.gallery div[active=true]'));
		return false;
	});

	$('#gallery_right').live('click', function(event) {
		nextImage($('.gallery div[active=true]'));
		return false;
	});
	
	// Gallery key listener
	$(document).keydown(function(event) {
		if(event.keyCode == '37') {
			prevImage($('.gallery div[active=true]'));
			event.preventDefault();
		} else if (event.keyCode == '39') {
			nextImage($('.gallery div[active=true]'));
			event.preventDefault();
		}
	});
	
	// If gallery is available, load first image
	initGallery();
	
	$('#side_navigation').live('mouseenter, mousemove', function(event) {
		showScreen();
	});
	
	$('#navigation').live('mouseenter, mousemove', function(event) {
		showScreen();
	});
	
	$('.project_description').live('mouseenter, mousemove', function(event) {
		showScreen();
	});
	
});

// AJAX
function initOnStateChangeHandler() {
	$(window).bind('statechange',function(){
		// Prepare Variables
		var
			State = History.getState(),
			url = State.url,
			relativeUrl = url.replace('http://www.haubitz-zoche.de',''),
			data = State.data;
		var contentHeight = $('#content').height();
		if((data.nav.activeItem != activeStateData.nav.activeItem || data.nav.activeSubitem != activeStateData.nav.activeSubitem) || (activeStateData.side.id == 'none')) {
			//console.log('generalRequest');
			// generalRequest
			$('.nav_item a').removeClass('active').css('color', '#000');
			$('#'+data.nav.activeItem).addClass('active');
			$('.sub_item').css('display', 'none').attr('active', 'false');
			//console.log('rel '+$('#'+data.nav.activeItem).attr('rel'))
			$('.sub_item[rel="'+ $('#'+data.nav.activeItem).attr('rel') +'"]').css('display', 'block').attr('active', 'true');
			$('.sub_item > a').removeClass('active');
			$('.sub_item[active=true] > a[rel=' + data.nav.activeSubitem + ']').addClass('active');
			
			$('#replaceable').fadeOut(200, function() {
				$('#content').height(contentHeight);
				$(this).remove();
				$('#content').load(url + ' #replaceable', function(){
					$('#content').css({'height': 'auto', 'min-height': '700px'});
				    $('#replaceable').css('display', 'none').fadeIn(100);
					initGallery();
					data.side.id = $('.side_list').attr('id');
					data.side.activeItem = $('.side_list a.active').attr('pid');
					data.main.pid = $('.side_list a.active').attr('pid');
					data.main.page = $('.side_list a.active').attr('page');
				});
				
			});
			
		} else {
			//console.log('mainRequest');
			if(data.side.id == '' && data.main.pid == '') {
				data.side.id = $('.side_list').attr('id');
				data.side.activeItem = $('.side_list a:first-child').attr('pid');
				data.main.pid = $('.side_list a:first-child').attr('pid');
				data.main.page = $('.side_list a:first-child').attr('page');
			}
			var $side = $('#'+data.side.id);
			// active element markieren
			$side.children('a').removeClass('active');
			$side.children('a[pid='+data.side.activeItem+']').addClass('active');
			$('#main_container').children().fadeOut(100, function() {
				$('#content').height(contentHeight);
				$(this).remove();
				$('#main_container').load(hosturl + '/ajax-' + data.main.page +'/',{
				 pid: data.main.pid },
				 function(){
					$('#content').css({'height': 'auto', 'min-height': '700px'});
				    $(this).children().css('display', 'none').fadeIn(100);
					initGallery();
				});
			});
		}
		setqTransUrl(url);
		csStartTimer = true;
		activeStateData = data;
		
	});
}


function setTitle() {
	return $('#main_container').children('div:first-child').find('.headline').html();
}


// GALLERY

function initGallery() {
	$('.gallery').height($('.gallery div:first-child').attr('imgheight'));
	loadImage($('.gallery div:first-child'), false);
	changeLabels($('.gallery div:first-child'));
	$('a').dwFadingLinks({
	    color: '#0a7098',
	    duration: 150
	  });
	$('#show_video').click(function(event) {
		showVideo();
		return false;
	});
}

function centerView() {
	//$.scrollTo($('.gallery').offset().top - 20, 600, {easing: 'easeOutQuart'});
}

function changeLabels(img_div) {
	$('#gallery_index').html($(img_div).attr('pos'));
	$('#gallery_title').html($(img_div).attr('title'));
}

function isRightHalf(mouse_x, div_x, div_width) {
	centre = div_width / 2;
	return mouse_x - div_x > centre;
}

function nextImage(img_div) {
	if(csStartTimer)
		clearScreen();
	var next_img;
	
	$(img_div).attr('active', 'false');
	$(img_div).parent().height($(img_div).attr('imgheight'));
	$(img_div).children().fadeOut(50, function() {
	
		if ($(img_div).next().length == 0) {
			next_img = $(img_div).parent().children('div:first-child');
		} else {
			next_img = $(img_div).next();
		}
		changeLabels(next_img);
		$(img_div).parent().animate({height: $(next_img).attr('imgheight')}, 200, 'easeOutQuart', function() {
			if($(img_div).hasClass('video')) $(img_div).html('');
			if ($(next_img).hasClass('video')) {
				$(next_img).attr('active', 'true');
				$(next_img).css('display', 'block').append('<iframe src="http://player.vimeo.com/video/'+ $(next_img).attr('url') +'?title=0&amp;byline=0&amp;portrait=0" width="580" height="326" frameborder="0"></iframe>');
			} else {
				if($(next_img).attr('rel') == 'loaded') {
			  		$(next_img).attr('active', 'true');
			  	  $(next_img).children().fadeIn(50);
			  	  centerView();
			  	} else {
			  	  loadImage(next_img, true);
			  	}
			}
		})
	})
}

function showVideo() {
	var img_div = $('.gallery div[active=true]');
	var next_img;
	$(img_div).attr('active', 'false');
	$(img_div).parent().height($(img_div).attr('imgheight'));
	$(img_div).children().fadeOut(50, function() {
		next_img = $(img_div).parent().children('div.video:first');
	
		changeLabels(next_img);
		$(img_div).parent().animate({height: $(next_img).attr('imgheight')}, 200, 'easeOutQuart', function() {
			if($(img_div).hasClass('video')) $(img_div).html('');
			if ($(next_img).hasClass('video')) {
				$(next_img).attr('active', 'true');
				$(next_img).css('display', 'block').append('<iframe src="http://player.vimeo.com/video/'+ $(next_img).attr('url') +'?title=0&amp;byline=0&amp;portrait=0" width="580" height="326" frameborder="0"></iframe>');
			} else {
				if($(next_img).attr('rel') == 'loaded') {
			  		$(next_img).attr('active', 'true');
			  	  $(next_img).children().fadeIn(50);
			  	  centerView();
			  	} else {
			  	  loadImage(next_img, true);
			  	}
			}
		})
		
	})
	
}

function prevImage(img_div) {
	if(csStartTimer)
		clearScreen();

	var prev_img;
	
	$(img_div).attr('active', 'false');
	$(img_div).parent().height($(img_div).attr('imgheight'));
	$(img_div).children().fadeOut(50, function() {
	
		if ($(img_div).prev().length == 0) {
			prev_img = $(img_div).parent().children('div:last-child');
		} else {
			prev_img = $(img_div).prev();
		}
		changeLabels(prev_img);
		$(img_div).parent().animate({height: $(prev_img).attr('imgheight')}, 200, 'easeOutQuart', function() {
			if($(img_div).hasClass('video')) $(img_div).html('');
			if ($(prev_img).hasClass('video')) {
				$(prev_img).attr('active', 'true');
				$(prev_img).css('display', 'block').append('<iframe src="http://player.vimeo.com/video/'+ $(prev_img).attr('url') +'?title=0&amp;byline=0&amp;portrait=0&amp;color=0a7098" width="871" height="490" frameborder="0"></iframe>');
			} else {
				if($(prev_img).attr('rel') == 'loaded') {
			  		$(prev_img).attr('active', 'true');
			  	  $(prev_img).children().fadeIn(50);
			  	  centerView();
			  	} else {
			  	  loadImage(prev_img, true);
			  	}
			}
		})
	})
}

function loadImage(img_div, center_view) {
	var img = new Image();
	$('#ajax-loader').css('display', 'block');
	$(img)
	  // once the image has loaded, execute this code
		.load(function () {
		// set the image hidden by default    
		$(this).hide();
		$('#ajax-loader').css('display', 'none');
		
		// with the holding div, apply:
		$(img_div).append(this).width($(img_div).attr('imgwidth')).attr('active', 'true');
		
		// fade our image in to create a nice effect
		$(this).fadeIn(50);
		if(center_view)
			centerView();
		})
		
		// if there was an error loading the image, react accordingly
		.error(function () {
		  // notify the user that the image could not be loaded
		})
		
		// *finally*, set the src attribute of the new image to our image
		.attr({src: $(img_div).attr('url'),
				width: $(img_div).attr('imgwidth'),
				height: $(img_div).attr('imgheight'),
				border: "0"});
		$(img_div).attr('rel', 'loaded');
}

function setqTransUrl(url) {
	url = url.replace('http://www.haubitz-zoche.de/en/', '');
	url = url.replace('http://www.haubitz-zoche.de/', '');
	//console.log(url);
	$('.qtrans_language_chooser li a').each(function(index) {
	  $(this).attr('href', "http://www.haubitz-zoche.de/"+$(this).attr('hreflang')+"/"+url);
	});
}

function clearScreen() {
	csStartTimer = false;
	$('#side_navigation').animate({'opacity':'0.01'}, 200);
	$('#sub_navigation').animate({'opacity':'0.01'}, 200);
	$('.project_description').animate({'opacity':'0.01'}, 200);
	$('#footer').animate({'opacity':'0.01'}, 200);
}

function showScreen() {
	csStartTimer = true;
	$('#side_navigation, .project_description, #footer, #sub_navigation').stop(true).animate({'opacity':'1'}, 100);
}

