$(document).ready(function() {
	
	// init home page tooltip
	var initQualitySignTooltip = function() {	
		xOffset = 30;
		yOffset = 130;
		$('#quality-sign').each(function() {
			$(this).hover(function(e) {							  
				$(this).append('<div id="quality-tooltip"></div>');
				$('#quality-tooltip').css('top', (e.pageY - yOffset) + 'px').css('left', (e.pageX + xOffset) + 'px').fadeIn('fast');
		    }, function() {
				$('#quality-tooltip').remove();
		    });	
			$(this).mousemove(function(e) {
				$('#quality-tooltip').css('top', (e.pageY - yOffset) + 'px').css('left', (e.pageX + xOffset) + 'px');
			});
		})
	};
	initQualitySignTooltip();
	
	// home page cluster carousel
	$('#cluster-selection').each(function() {
		var auto_rotate = true;
		var cluster = $(this);
		// hide the list
		$('ul', cluster).hide();
		var number_of_clusters = $('ul li', cluster).length; 
		var current_index = 0;
		// rotation logic
		var rotate = function(to) {
			// handle offset and calc pos
			var orientation = to || 'left';
			if(orientation != 'left') orientation = 'right';
			if(orientation == 'right') {
				current_index--;
			} else {
				current_index++;
			}
			if(current_index > (number_of_clusters - 1)) {
				current_index = 0;
			}
			if(current_index < 0) {
				current_index = (number_of_clusters - 1);
			}
			// call
			makeCurrent(current_index);
		};
		var makeCurrent = function(index) {
			var pos = index || 0;
			// fetch the new current item
			var current = $('li:eq('+pos+')', cluster);
			// fetch previous item
			if(pos == (number_of_clusters - 1)) { var next = $('li:eq(0)', cluster); } else { var next = $('li:eq('+(pos + 1)+')', cluster); }
			// fetch next item
			if(pos == 0) { var prev = $('li:eq('+(number_of_clusters - 1)+')', cluster); } else { var prev = $('li:eq('+(pos - 1)+')', cluster); }
			// fade out
			$('.cs-c').fadeOut('fast', function() {
				// inject content
				$('.cs-ui-cur .cs-c').html($(current).html());
				$('.cs-ui-left .cs-c').attr('class', 'cs-c ' + $(prev).attr('class'));
				$('.cs-ui-right .cs-c').attr('class', 'cs-c ' + $(next).attr('class'));	
				$('.cs-c').fadeIn('fast');
			});
		};
		// jump to current url
		var goTo = function() {
			var url = $('.cs-c-con a:first').attr('href');
			document.location.href = url;
		};
		if(number_of_clusters > 2) { // only show carousel if more than 2 items
			// build the ui
			var ui_content = '<div class="cs-ui-left cs-ui-h"><div class="cs-c"></div></div><div class="cs-ui-cur"><div class="cs-ui-cur-i"><div class="cs-p-left"><a href="#" title="zurück"><span>zurück</span></a></div><div class="cs-c cs-c-con"></div><div class="cs-p-right"><a href="#" title="vor"><span>vor</span></a></div></div></div><div class="cs-ui-right cs-ui-h"><div class="cs-c"></div></div>';
			$(cluster).append(ui_content);
			// init
			makeCurrent(current_index);
			// bind events
			$('.cs-p-left a, .cs-ui-left').bind('click', function() {
				rotate('right');
				auto_rotate = false;
				return false;
			});
			$('.cs-p-right a, .cs-ui-right').bind('click', function() {
				rotate('left');
				auto_rotate = false;
				return false;
			});
			$('.cs-c-con').bind('click', function() {
				goTo();
				return false;
			});
			setInterval( function() {
				if(auto_rotate) {
					rotate('left');
				}
			}, 5000);
		}
	});

	// handle tipped form inputs
	$('form').formtips({ 
		class_name: 'tipped'
	});
	
	// init date calendar
	$('input.date').calendar();
	
	// we want to scroll down the callback details
	var toggleCallbackDetails = function() {
		if($('input#callback').is(':checked')) {
			$('.callback-info').slideDown('fast');
		} else {			
			$('.callback-info').slideUp('fast');
		}
	};
	$('input#callback').click(function() {
		toggleCallbackDetails();
	});
	toggleCallbackDetails();
	
	
	// accordion
	var initAccordeon = function() {
		var accordionClicked = false; // track user interaction
		$('.accordion dt').addClass('hidden');
		$('.accordion dd').hide();
		$('.accordion dt span').click(function() {
			accordionClicked = true;
			var cont = $(this).parent().next('dd');
			var f = function(obj) {
				if($(obj).parent().find(':hidden').length > 0) {
					$(obj).slideDown('fast', function() {
						$(this).prev().addClass('visible').removeClass('hidden');
					});
				} else {
					$(obj).slideUp('fast', function() {	
						$(this).prev().addClass('hidden').removeClass('visible');
					});	
				}
			}
			if($('.accordion dd:visible').length > 0) {
				var t = $('.accordion dd:visible');
					$(t).slideUp('fast', function() {
						if($(t)[0] != $(cont)[0]) {
							f(cont);
						}
						$(this).prev().addClass('hidden').removeClass('visible');
					});
			} else {
				f(cont);
			}
		});
		setTimeout(function() {
			if(!accordionClicked) {
				$('.accordion.auto-open dt:first span').click(); // open first item
			}
		}, 1500);
	}
	initAccordeon();

	// tooltips
	$('.tooltipped').qtip({
		content: false,
		show: 'mouseover',
		hide: 'mouseout',
		position: {
			corner: {
		    	tooltip: 'bottomMiddle',
				target: 'topMiddle'
			}
		},
		style: { 
			tip: true,
			width: 180,
	      	padding: 3,
	      	background: '#0d1c34',
	      	color: '#FFF',
			textAlign: 'center',
			border: {
				width: 5,
				radius: 5,
		      	color: '#0d1c34'
			}
		},
		api: {
			beforeShow: function() {
				var content = '';
				if(this.elements.target.parent().is('.active')) {
					content = 'von Auswahl entfernen';
				} else {
					content = 'zu Auswahl hinzufügen';
				}
				this.updateContent(content);
			}
		}
	});
	
	// advanced cluster panel
	$('.cluster-panel').each(function() {
		// provide tooltip handler
		$('label.tooltipped', this).each(function() {
		});
		// check for selected items
		$('input:checked', this).each(function() {
			$(this).parent().addClass('active');
		});
		// handle click event for labels
		$('label', this).click(function() {
			var do_check = function(elem) {
				if(jQuery.browser.msie) {
					$(elem).attr('checked', 'checked');
				} else {
					$(elem).checked = true;
				}
			};
			var do_uncheck = function(elem) {
				if(jQuery.browser.msie) {
					$(elem).removeAttr('checked');
				} else {
					$(elem).checked = false;
				}
			};
			if($(this).parent().is('.active')) {
				$(this).parent().removeClass('active');
				// uncheck
				do_uncheck($(this).parent().find('input'));
			} else {
				// check
				do_check($(this).parent().addClass('active'));
			}
			$(this).qtip('hide').qtip('show');
			// handle "select all" 
			if($(this).parent().is('#c_all')) {
				if($(this).parent().is('.active')) {
					// select all
					$(this).parent().parent().find('.cluster').each(function() {
						$(this).addClass('active');
						do_check($(this).find('input'));
					});
				} else {
					// unselect all
					$(this).parent().parent().find('.cluster').each(function() {
						$(this).removeClass('active');
						do_uncheck($(this).find('input'));
					});
				}
			}
			// submit form
			$(this).parent().parent().parent('form').submit();
		});
	});
	$('.cluster-panel.cp-advanced .adv').each(function() {
		$('.adv-c', this).each(function() {
			if(!$(this).parent().is('.open')) {
				// hide the panel by default
				$(this).hide();
			}
		}); 
		// handle link
		$('h4', this).click(function() {
			if($(this).parent().is('.open')) {
				// close panel
				$(this).parent().find('.adv-c').slideUp('slow');
				$(this).parent().removeClass('open');
			} else {
				// open panel
				$(this).parent().find('.adv-c').slideDown('slow');
				$(this).parent().addClass('open');
			}
		});
	});
	
	// handle downloads ajax form 
	$('form#downloads').bind('submit', function() {	
		var url = $(this).attr('action') + '?type=3';
		var params = {};
		$('form#downloads div.cluster').each(function() {
			if($(this).is('.active')) {
				// add active cluster to params
				params[$('input', this).attr('name')] = 1;
			}
		});
		$('#download-results').height($('#download-results-inner').height());
		$('#download-results-inner').fadeOut('fast', function() {});
		jQuery.post(url, params, function(data) {
			var content = data;
			$('#download-results-inner').empty().append(content).fadeIn('fast');
			$('#download-results').height($('#download-results-inner').height());
			return false;
		});
		return false;
	});
	
	// handle seminars ajax form 
	$('form#seminar-suche').bind('submit', function() {	
		var url = $(this).attr('action') + '?type=5';
		var params = {};
		$('form#seminar-suche div.cluster').each(function() {
			if($(this).is('.active')) {
				// add active cluster to params
				params[$('input', this).attr('name')] = 1;
			}
		});
		// add advanced filters
		params['tx_pgseminar_pi2[seminar_location]'] = $('select#seminar_location', this).val();
		params['tx_pgseminar_pi2[seminar_title]'] = $('select#seminar_title', this).val();
		params['tx_pgseminar_pi2[date_start]'] = $('input#date_start', this).val();
		params['tx_pgseminar_pi2[date_end]'] = $('input#date_end', this).val();
		// handle post and result
		$('#seminar-list').height($('#seminar-list-inner').height());
		$('#seminar-list-inner').fadeOut('fast', function() {});
		jQuery.post(url, params, function(data) {
			var content = data;
			$('#seminar-list-inner').empty().append(content).fadeIn('fast');
			$('#seminar-list').height($('#seminar-list-inner').height());
			// re-init handlers
			initSeminars();
			return false;
		});
		return false;
	});
	var initSeminars = function() {
		$('#seminar-list table th a').click(function() {
			var link = $(this);
			$('#seminar-list').height($('#seminar-list-inner').height());
			$('#seminar-list-inner').fadeOut('fast', function() {
				var url = $(link).attr('href') + '&type=5';
				$(this).load(url, function(data) {
					var content = data;
					$('#seminar-list-inner').empty().append(content).fadeIn('fast');
					$('#seminar-list').height($('#seminar-list-inner').height());
					initSeminars();
				});
			});
			return false;
		});
	}
	initSeminars();
	
	// handle faq form
	$('form#faq-filter').each(function() {
		var form = $(this);
		var action = $(form).attr('action') + '?type=6';
		$('select', form).bind('change', function() {
			var options = {
				beforeSubmit: 	function(formData, jqForm, options) {
					$('#accordeon-wrap').fadeOut('fast', function() {
					});
				},
				success: 		function(responseText, statusText) {
					var content = responseText;
					$('#accordeon-wrap-inner').empty().append(content);
					// re-init accordeon
					initAccordeon();
					$('#accordeon-wrap').fadeIn('fast');
					return false;
				},
				type: 			'post',
				url: 			action
			};
			$(form).ajaxSubmit(options);
			return false;
		});
	});
	
	// lets calculate the total value of booking signup
	$('form#signup').each(function() {
		var form = $(this);
		$('select#participants', form).change(function() {
			var num = parseFloat($(this).val());
			var price = parseFloat($('#price', form).val());
			var total = '-';
			if(num > 0 && price > 0) {
				// format the number
				total = parseFloat(num * price);
				var k = (Math.round(total * 100) / 100).toString();
				k += (k.indexOf('.') == -1)? '.00' : '00';
				var p = k.indexOf('.'), m = k.indexOf('-.');
				var f = (p == 0 || m == 0)? '0,' : ',';
				total = k.substring(0, p) + f + k.substring(p+1, p+3);
				total = total.replace('.', ',') + ' €';
			}
			$('#total', form).val(total);
		});
		$('select#participants', form).change();
	});
	
	// hide faq filter button
	$('form.filter button').hide();
	
	// process employee chart
	$('#employees').each(function() {
		var c = $(this);
		var number_of_employees = $('.employee', this).length;
		var employees = [];
		var tags = {};
		var tags_total = 0;
		var employee = function() {
			this.id;
			this.elementId;
			this.name = '';
			this.tags = [];
			this.enabled = true;
			this.hasTag = function(tagName) {
				for(var i = 0; i < this.tags.length; i++) {
					if(this.tags[i] == tagName) {
						return true;
					}
				}	
				return false;
			};
			this.enable = function() {
				$('#' + this.elementId).addClass('enabled').removeClass('disabled');
				$('#' + this.elementId).fadeTo(500, 1);
				this.enabled = true;
			};
			this.disable = function() {
				$('#' + this.elementId).addClass('disabled').removeClass('enabled');
				$('#' + this.elementId).fadeTo(200, 0.3);
				this.enabled = false;
			};
			this.setAsFirst = function() {
				$('#' + this.elementId).prependTo('#employees');
			};
			this.setAsLast = function() {

			};
		};
		var filterById = function(id) {
			for(var i = 0; i < employees.length; i++) {
				var e = employees[i];
				if(e.id == id || id == 0) {
					// enable
					e.enable();
				} else {
					// disable
					e.disable();
				}
			}	
			// handle header tags
			$('#tagcloud span.active').removeClass('active');
			reorder();
		};
		var filterByTag = function(tagName) {
			for(var i = 0; i < employees.length; i++) {
				var e = employees[i];
				if(e.hasTag(tagName) || tagName == '') {
					// enable
					e.enable();
				} else {
					// disable
					e.disable();
				}
			}	
			// handle header tags
			$('#tagcloud span.active').removeClass('active');
			$('#tagcloud span:contains('+tagName+')').addClass('active');
			reorder();
		};
		var calculateTagSize = function(count, total) {
			var fontMax = 10;
			var fontMin = 1;
			var steps = fontMax - fontMin;
			var share = Math.floor((count / total) * 100);
			var addSteps = Math.round((share / 100) * steps);
			return (fontMin + addSteps);
		}
		var reorder = function() {
			for(var i = 0; i < employees.length; i++) {
				var e = employees[i];
				if(e.enabled) {
					// bring to front
					e.setAsFirst();
				} else {
					// bring to back
					e.setAsLast();
				}
			}
		}
		// get dem employees
		$('.employee', this).each(function(i, val) {
			// add a unique id
			var elementId = 'emp-' + i;
			$(this).attr('id', elementId).attr('rel', elementId);
			// create employee object
			var e = new employee();
			e.id = $('span.id', this).text();
			e.elementId = elementId;
			e.name = $('h4 a', this).attr('title');
			// add tags
			$('ul.tags li', this).each(function() {
				var tagItem = $(this).text();
				e.tags.push(tagItem);
				// add tag to tag collection
				var b = 0;
				tags_total++;
				for (t in tags) {
					b++;
					if(t == tagItem) {
						// increase counter
						tags[tagItem] = tags[tagItem] + 1;
					} else {
						tags[tagItem] = tags[tagItem] || 1;
					}
				}
				if(b == 0) {
					// add tag
					tags[tagItem] = 1;
				}
			});
			// add employee to list
			employees.push(e);
			// manipulate url to show ajaxified view
			$('a', this).each(function() {
				$(this).attr('href', $(this).attr('href') + '&type=4');
			});
		});	
		// write the tag cloud
		$('#tagcloud').html('<table style="margin: 0; padding: 0; height: 175px;"><tr><td class="target"></td></tr></table>');
		for (t in tags) {
			var s = calculateTagSize(tags[t], tags_total);
			$('#tagcloud .target').append('<span class="t' + s + '">' + t + '</span> ');
		}
		$('#tagcloud span').bind('click', function() {
			filterByTag($(this).text());
			$('#employee-filter select#area').val($(this).text());
		});
		// handle name filter
		$('#employee-filter select#name').change(function() {
			var val = $(this).val();
			filterById(val);
			$('#employee-filter select#area').val(0);
		});
		// handle tag filter
		$('#employee-filter select#area').change(function() {
			var val = $(this).val();
			filterByTag(val);
			$('#employee-filter select#name').val(0);
		});
	});
	
	// handle external links (open in new window)
	$('a.external').click(function() {
		var url = $(this).attr('href');
		window.open(url, 'external');
		return false;
	});
	
});
