var rollOutSpeed = 1000;
jQuery.easing.def = 'easeOutQuint';

var newsHeight = 250; // height of news overview container
var newsDetailHeight = 500; // height of news detail container
var showcaseHeight = 300; // height of showcase overview container

function pageload(hash) {
	if(hash) {
		// handle request
		switch(hash) {
			case 'kontakt':
				closeAllOpenPanels();
				tb_show(null, '/kontakt?height=500&amp;width=700');
				break;
			case 'impressum':	
				closeAllOpenPanels();
				tb_show(null, '/impressum?height=500&amp;width=600');
				break;
			case 'jobs':
				// close all open panels
				closeAllOpenPanels();
				tb_show(null, '/jobs?height=500&amp;width=600');
				break;	
			case 'news':
				tb_remove(); // close tb
				// close all open panels
				if($('.panel.visible').length > 0) {
					closeAllOpenPanels(function() { 
						loadNewsOverview();
					}, 'news');	
				} else {
					loadNavigationItem('news');
				}
				break;
			case 'showcase':
				tb_remove(); // close tb
				// close all open panels
				if($('.panel.visible').length > 0) {
					closeAllOpenPanels(function() { 
						loadShowcaseOverview();
					}, 'showcase');	
				} else {
					loadNavigationItem('showcase');
				}
				break;
			case 'index':
				tb_remove(); // close tb
				// close all open panels
				closeAllOpenPanels();
				break;
			default:
				tb_remove(); // close tb
				if(hash.match(/news-([0-9]+)/)) {
					// we have a news detail page
					var result = hash.match(/news-([0-9]+)/);
					var id = result[1];
					// load news item
					if($('#p-news').is('.visible')) {
						loadNewsItem(id);
					} else {
						closeAllOpenPanels(function() {
							loadNewsItem(id);
						});
					}
				} else if(hash.match(/showcase-([0-9]+)-image-([0-9]+)/)) {
					// we have a showcase detail page with a certain image selected				
					var result = hash.match(/showcase-([0-9]+)-image-([0-9]+)/);
					var id = result[1];
					var image_id = result[2];
					if($('#p-showcase').is('.visible')) {
						// image loading is enough
						loadShowcaseImageData(image_id);
					} else {
						// load showcase item completely
						closeAllOpenPanels(function() {
							loadShowcaseItem(id, image_id);	
						});
					}
				} else if(hash.match(/showcase-([0-9]+)/)) {
					// we have a showcase detail page
					var result = hash.match(/showcase-([0-9]+)/);
					var id = result[1];
					// load showcase item
					if($('#p-showcase').is('.visible')) {
						loadShowcaseItem(id);
					} else {
						closeAllOpenPanels(function() {
							loadShowcaseItem(id);
						});
					}
				} else {
					// load a main menu item
					loadNavigationItem(hash);
				}
				break;
		}
	} else {
		// show start page
		tb_remove();
		closeAllOpenPanels();
	}
	$('.fh h2 a').click(function() {
		var a = $(this).parent().attr('id').replace('h-', '');
		handleNavigationItem(a);
		return false;
	});
}

$(document).ready(function() {
	
	// add js class to body
	$('body').addClass('js');

	// init history plugin
	$.historyInit(pageload);
	
	// handle history plugin for thickbox pages
	$('.thickbox').click(function() {
		var hash = $(this).attr('rel');
		hash = hash.replace(/^.*#/, '');
		$.historyLoad(hash);
	});
	
	// connect navi link urls to panels 
	$('.fh h2 a').each(function() { $(this).parent().parent().attr('rel', $(this).attr('href')); });
	
	// init flash
	initFlash();
	
	// init main accordion
	initAccordion();
	
	// init components
	initComponents();
	
	// handle header logo click
	$('#header h1 a').click(function() {
		// close all other opened panels
		$.historyLoad('index');
		return false;
	});
	
	// handle jobs click
	$('#f-jobs a').click(function() {
		// lets open the jobs box
		handleJobsLink();
		return false;
	});

	// handle imprint click
	$('#f-impressum a').click(function() {
		// lets open the imprint box
		handleImprintLink();
		return false;
	});

	// handle contact click
	$('#f-kontakt a').click(function() {
		// lets open the imprint box
		handleContactLink();
		return false;
	});
	
	// try to find inital opened container and open it
	$('.panel.init').each(function() {
		var pid = $(this).attr('id');
		var key = pid.substr(2, (pid.length - 2))
		handleNavigationItem(key);
	});
	
    // lets do the day mode switcher
    $('#daytime-switch .switch-link').each(function () {
    	var distance = -60;
    	var time = 400;
    	var hideDelay = 500;
    	var hideDelayTimer = null;
    	var beingShown = false;
    	var shown = false;
    	var trigger = $('.trigger', this);
    	var info = $('.bubble', this).css('opacity', 0);
    	var popup_height = $(info).height();
    	var popup_width = $(info).width();
    	$([trigger.get(0), info.get(0)]).mouseover(function () {
    		if (hideDelayTimer) clearTimeout(hideDelayTimer);
    		if (beingShown || shown) {
    			return; // don't trigger the animation again
    		} else {
    			// reset position of info box
    			beingShown = true;
    			info.css({
    				top: ($(trigger).offset().top - distance -10),
    				left: (-10),
    				display: 'block'
    			}).animate({
    				top: '+=' + distance + 'px',
    				opacity: 1
    			}, time, 'swing', function() {
    				beingShown = false;
    				shown = true;
    			});
    		}
    		return false;
    	}).mouseout(function () {
    		if (hideDelayTimer) clearTimeout(hideDelayTimer);
    		hideDelayTimer = setTimeout(function () {
    			hideDelayTimer = null;
    			info.animate({
    				top: '-=' + distance + 'px',
    				opacity: 0
    			}, time, 'swing', function () {
    				shown = false;
    				info.css('display', 'none');
    			});
    		}, hideDelay);
    		return false;
    	});
    });
    $('#daytime-switch a.trigger, #daytime-switch .link a').click(function() {
		var link = $(this);
		if($(link).parent().is('.day')) {
			// switch to night mode
			$('#daytime-switch').fadeOut('slow', function() {
				$('body').fadeOut('slow', function() {
					$('.switch-link').removeClass('current');
					$('.switch-link.night').addClass('current');
					daytime_mode = 'night';
					initFlash();
					$('link[title=layout]').attr('href', '/css/layout_night.css');
					$('#daytime-switch').fadeIn('fast');
					$('body').fadeIn('slow');
				});
			});
		} else {
           // switch to day mode	
			$('#daytime-switch').fadeOut('slow', function() {
				$('body').fadeOut('slow', function() {
					$('.switch-link').removeClass('current');
					$('.switch-link.day').addClass('current');
					daytime_mode = 'day';
					initFlash();
					$('link[title=layout]').attr('href', '/css/layout_day.css');
					$('#daytime-switch').fadeIn('fast');
					$('body').fadeIn('slow');
				});
			});
		}
		return false; 
	});
	
});

var closeAllOpenPanels = function(callback, except) {
	if (callback == null){
		callback = function() {}
	}
	if($('.panel.visible').length > 0) {
		$('.panel.visible').each(function() {
			var doIt = true;
			if(except != null && $(this).is('#p-' + except)) {
				doIt = false;
				callback();
			}
			if(doIt) {
				var pa = $(this);
				$('.panel-inner', pa).fadeOut('slow', function() {
					$(pa).addClass('hidden').removeClass('visible').slideUp(rollOutSpeed, function() {
						// remove content
						$('.panel-inner').empty();
						callback();
					});
				});
			}
		});
	} else {
		callback();
	}
}

var handleShowcaseItem = function(id) {
	var hash = 'showcase-' + id;
	$.historyLoad(hash);
}

var handleNewsItem = function(id) {
	var hash = 'news-' + id;
	$.historyLoad(hash);
}

// handle the showcase links
var loadShowcaseItem = function(id, image_id) {
	// init image id
	if(image_id == null) image_id = 0;
	var p = $('#p-showcase');
	// add loading status
	$(p).addClass('loading');
	var url = '/showcase/detail/id/' + id;
	// do the ajax
	$('.panel-inner', p).fadeOut('slow', function() {
		$(p).addClass('visible').removeClass('hidden');
		$(p).animate({ // resize the container
			height: 500
		}, 1000, 'easeOutQuint', function() {
			$('.panel-inner', p).load(url, {}, function() {
				// remove loading status
				$(p).removeClass('loading');
				// fade in
				$('.panel-inner', p).fadeIn('slow', function() {
					// re-init components
					initComponents();
					initShowcase(id, image_id);	
				});
			});
		});
	});	
	// info block toggle
	$('#showcase-content-description').addClass('hidden');
	$('#info-button').mouseover(function() {
		$('#showcase-content-description.hidden').fadeIn('fast', function() {
			$(this).addClass('visible').removeClass('hidden');
		});
	}).mouseout(function() {
		$('#showcase-content-description.visible').fadeOut('fast', function() {
			$(this).addClass('hidden').removeClass('visbile');
		});
	});
}

var loadNewsItem = function(id) {
	var p = $('#p-news');
	// add loading status
	$(p).addClass('loading');
	var url = '/news/detail/id/' + id;
	$('.panel-inner', p).fadeOut('slow', function() {
		$(p).addClass('visible').removeClass('hidden');
		$(p).animate({ // resize the container
			height: newsDetailHeight
		}, 1000, 'easeOutQuint', function() {
			// load url after resize
			$('.panel-inner', p).load(url, function() {
				// remove loading status
				$(p).removeClass('loading');
				// fade in
				$('.panel-inner', p).fadeIn('slow', function() {
					// re-init components
					initComponents();
				});
			});	
		});
	});
}

var handleShowcaseOverview = function() {
	var hash = 'showcase';
	$.historyLoad(hash);
}

var handleNewsOverview = function() {
	var hash = 'news';
	$.historyLoad(hash);
}

var handleContactLink = function() {
	var hash = 'kontakt';
	$.historyLoad(hash);
}

var handleImprintLink = function() {
	var hash = 'impressum';
	$.historyLoad(hash);
}

var handleJobsLink = function() {
	var hash = 'jobs';
	$.historyLoad(hash);
}

var loadShowcaseOverview = function() {
	var p = $('#p-showcase');
	// add loading status
	$(p).addClass('loading');
	var url = '/showcase';
	$('.panel-inner', p).fadeOut('slow', function() {
		$(p).addClass('visible').removeClass('hidden');
		$(p).animate({ // resize the container back to overview height
			height: showcaseHeight
		}, 1000, 'easeOutQuint', function() {
			$('.panel-inner', p).load(url, {}, function() {
				// remove loading status
				$(p).removeClass('loading');
				// fade in
				$('.panel-inner', p).fadeIn('slow', function() {
					// re-init components
					initComponents();
				});
			});
		});
	});
}

var loadNewsOverview = function() {
	var p = $('#p-news');
	// add loading status
	$(p).addClass('loading');
	var url = '/news';
	$('.panel-inner', p).fadeOut('slow', function() {
		$(p).addClass('visible').removeClass('hidden');
		$(p).animate({ // resize the container back to overview height
			height: newsHeight
		}, 1000, 'easeOutQuint', function() {
			$('.panel-inner', p).load(url, {}, function() {
				// remove loading status
				$(p).removeClass('loading');
				// fade in
				$('.panel-inner', p).fadeIn('slow', function() {
					// re-init components
					initComponents();	
				});
			});
		});
	});
}

// init components
var initComponents = function() {
	
	// image mouseover
	$('img').bind('mouseover', function() {
		$(this).addClass('hover');
	}).bind('mouseout', function() {
		$(this).removeClass('hover');
	});
	
	// add mouseover to overview items in showcase container
	$('#showcase-wrapper div.pi h3 a').each(function() {
		var l = $(this);
		$(this).parent().parent().click(function() {
			$(l).click();
		});
	});
	$('#showcase-wrapper div.pi').mouseover(function() {
		$(this).addClass('hover');
	});
	$('#showcase-wrapper div.pi').mouseout(function() {
		$(this).removeClass('hover');
	});
	
	// init external link helper
	initExternalLinks();
	
	// handle news links
	$('ul#news-overview li a').click(function() {
		var id = $(this).attr('rel');
		handleNewsItem(id);
		return false;
	});
	
	// handle showcase links
	$('.pi').bind('click', function() {
		var id = $(this).attr('rel');
		handleShowcaseItem(id);
		return false;
	});
	
	// news overview link
	$('#news-detail a.close').bind('click', function() {
		handleNewsOverview();
		return false;
	});
	
	// news thickbox links
	tb_init('a.thickbox');
	
	// handle form tips
	handleFormTips();
	
	// handle contact form 
	handleContactForm();
	
	// handle philosophy accordion
	var accordionClicked = false; // track user interaction
	$('#we-do dt').addClass('hidden');
	$('#we-do dd').hide();
	$('#we-do dt').click(function() {
		accordionClicked = true;
		var cont = $(this).next('dd');
		var f = function(obj) {
			if($(obj).parent().find(':hidden').length > 0) {
				$(obj).slideDown('slow', function() {
					$(this).prev().addClass('visible').removeClass('hidden');
				});
			} else {
				$(obj).slideUp('slow', function() {	
					$(this).prev().addClass('hidden').removeClass('visible');
				});	
			}
		}
		if($('#we-do dd:visible').length > 0) {
			var t = $('#we-do dd:visible');
				$(t).slideUp('slow', function() {
					if($(t)[0] != $(cont)[0]) {
						f(cont);
					}
					$(this).prev().addClass('hidden').removeClass('visible');
				});
		} else {
			f(cont);
		}
	});
	setTimeout(function() {
		if(!accordionClicked) {
			$('#we-do dt:first').click(); // open first item
		}
	}, 1500);
}

// handle the contact form
var handleContactForm = function() {
	var container = $('#error_container');
	jQuery.validator.addMethod('equalsNot', function(value, element, param) {
		return value != param;
	});
	var validateForm = jQuery("#contact_form").validate({
		submitHandler: function(form) {
			jQuery(form).ajaxSubmit({
				success: function(data) {
					$('#contact_form').slideUp('slow');
				},
				target: "#form-result"
			});
		},
		errorContainer: container,
		errorLabelContainer: $(container),
		wrapper: 'p',
		rules: {
			name: { required: true, equalsNot: 'Name, Vorname' },
			email: { required: true, email: true },
			message: { required: true, equalsNot: 'Nachricht' }
		}
	});
}

var initExternalLinks = function() {
	$('a.external').click(function() {
		var url = $(this).attr('href');
		window.open(url, 'external');
		return false;
	});
}

// init the index accordion
var initAccordion = function() {
	var acc = $('div#index-overview');
	$('h2 a', acc).click(function() {
		// dont follow link
		return false;
	});
}

// we got a new showcase opened
var loadShowcaseImageData = function(id) {
	var url = '/showcase/images/view/' + id;
	$.getJSON(url, function(json){
		// handle button click event
		jsonCallback(json);
	});
	var jsonCallback = function(json) {
		var f = '/files/showcases/images/full/'+json.filename;
		var type = (/[.]/.exec(json.filename)) ? /[^.]+$/.exec(json.filename) : undefined;
		var handleCallback = function(json, filename, filetype) {
			if(filetype == 'swf') {
				// show swf
				$('#showcase-content-inner').append('<div id="swflauncher"></div>') // insert image
				$('#showcase-content-inner div#swflauncher').fadeIn('slow', function() {
					// init swfobject
					var flashvars1 = new Object();
					var params1 = new Object();
					params1.wmode = 'transparent';
					var attributes1 = new Object();
					swfobject.embedSWF(filename, "swflauncher", "710", "439", "9.0.0", "/images/flash/expressInstall.swf", flashvars1, params1, attributes1 );	
				});
			} else {
				// show image
				$('#showcase-content-inner').append('<img src="'+filename+'" alt="" />') // insert image
				$('#showcase-content-inner img').fadeIn('slow', function() {
					// handle image click
					$(this).click(function() {
						if($('#pitem-right:visible').length > 0) {
							$('#pitem-right a').click();
						}
					});
				});
			}
			$('#page-info-current').text(json.current); // set current page number
			$('#page-info-total').text(json.total); // set total pages
			if(json.prev_id) {
				// show left button
				$('#pitem-left').show();
				$('#pitem-left a').attr('rel', json.prev_id).attr('href', '/showcase/images/view/' + json.prev_id);
			} else {
				$('#pitem-left').hide();
			}
			if(json.next_id) {
				// show right button
				$('#pitem-right').show();
				$('#pitem-right a').attr('rel', json.next_id).attr('href', '/showcase/images/view/' + json.next_id);
			} else {
				$('#pitem-right').hide();
			}
			$('#meta-page p:hidden').fadeIn('fast'); // show page info
		}
		if($('#showcase-content-inner img').length > 0) {
			$('#showcase-content-inner img').fadeOut('slow', function() {
				$('#showcase-content-inner img').remove();
				handleCallback(json, f, type);
			});	
		} else {
			handleCallback(json, f, type);
		}
	}
}
var initShowcase = function(id, image_id) {
	if(image_id == null || image_id == 0) image_id = $('#showcase-content').attr('rel');
	var initial_image_id = image_id;
	loadShowcaseImageData(initial_image_id);
	// handle button click (prev, next)
	$('.paging-item a').click(function() {
		$.historyLoad('showcase-' + id + '-image-' + $(this).attr('rel') + '');
		return false;
	});
	// back to overview links
	$('#meta-info p a').bind('click', function() {
		handleShowcaseOverview();
		return false;
	});
}

var loadNavigationItem = function(key) {
	// slide toggle panel
	var p = $('#p-'+key);
	var l = $('#fh-'+key);
	// handle click
	if($(p).is('.hidden')) {
		// show a panel
		var openPanel = function(panel) {
			// set containers back to original height
			$('#p-news').height(newsHeight);
			$('#p-showcase').height(showcaseHeight);
			// open panel
			$(panel).addClass('visible').removeClass('hidden').slideDown(rollOutSpeed, function() {
				// add loading status
				$(panel).addClass('loading');
				// load content
				$('.panel-inner', panel).hide().load($(l).attr('rel'), {}, function() {
					// remove loading status
					$(panel).removeClass('loading');
					// fade in
					$(this).fadeIn('slow', function() {
						// re-init components
						initComponents();	
					});
				});
			});
		}
		// close all other opened panels
		if($('.panel.visible').length > 0) {
			$('.panel.visible').each(function() {
				var pa = $(this);
				$(pa).addClass('hidden').removeClass('visible');
				$('.panel-inner', pa).fadeOut('slow', function() {
					$(pa).slideUp(rollOutSpeed, function() {
						// remove content
						$('.panel-inner').empty();
						// open panel
						openPanel(p);
					});
				});
			});
		} else {
			openPanel(p);
		}
	}
}

var handleNavigationItem = function(key) {
	var hash = key;
	hash = hash.replace(/^.*#/, '');
	$.historyLoad(hash);
}

// put the labels inside the form elements
var handleFormTips = function() {
    $('form').formtips({
        class_name: 'tipped'
    });
}
