/**
* Javascript
* JS: App
*
* @author Heiko Pfefferkorn (i-fabrik GmbH)
* @copyright 2010 i-fabrik GmbH
* @version $Id: app.min.js,v 1.9 2011-05-20 13:35:58 oliver Exp $
*
*/

(function($) {
	/**
	 * Alle Indizes eines JS-Objektes '{}' als Feld zurueckgeben
	 */
	$.extend({
		'getPlainObjectKeys': function(obj) {
			var keys = [];

			if( $.isPlainObject(obj) ) {
				$.each(obj, function(k) {
					keys.push(k);
				});
			}
			return keys;
		}
	});

	/**
	 * Automatische Transparenz
	 *
	 * <span class="opacity-{n}" />
	 * n = 1-10 (0=0, 1=0.1, ..., 10=1)
	 *
	 * @param options Object Parameter
	 */
	$.fn.parseOpacity = function(options) {
		var settings = { 'partOfClass': 'add-opacity_' };

		return this.each(function() {
			$.extend( settings, options );

			for( var i=0; i<=10; i++ ) {
				$(this).find('.'+settings.partOfClass+i).css('opacity', i/10);
			}
		});
	};

	$.fn.tagName = function() {
		var tagNames = null;

		if(1 === this.length) {
			tagNames = this[0].tagName.toLowerCase();
		} else {

			tagNames = [];

			this.each(function(i, el) {
				tagNames[i] = el.tagName.toLowerCase();
			});

		}

		return tagNames;
	};

	/**
	 * Erstes und letztes Element makieren
	 *
	 * @param m Mixed Selector oder das Element selbst
	 */
	$.fn.markFirstLastChild = function(options) {
		var settings = {
			'firstClass': 'is-first',
			'lastClass' : 'is-last'
		};

		return this.each(function() {
			$.extend( settings, options );

			$(this)
			.find('>:first-child').addClass(settings.firstClass).end()
			.find('>:last-child').addClass(settings.lastClass).end();
		});
	};

	/**
	 * Submit Closest Form
	 */
	$.fn.autoSubmit = function() {
		return this.each(function() {
			var tag = $(this).tagName();

			$(this).bind('doSubmit', function() {
				$(this).closest('form').submit();
			});

			if( tag=='select' ) {

				$(this).change( function(ev) {
					$(this).trigger('doSubmit');
				} );

			} else {

				$(this).click( function(ev) {
					ev.preventDefault();
					$(this).trigger('doSubmit');
				} );

				if( tag=='a' ) {
					$(this).keypress( function(ev) {
						ev.preventDefault();
						if( ev.keyCode==13 ) {
							$(this).trigger('doSubmit');
						}
					} );
				}

			}
		});
	};

	/**
	 * Tabellen - Zebraeffekt
	 */
	$.fn.zebra = function( options ) {
		var settings = {
			'classEven': 'even',
			'classOdd' : 'odd'
		};

		return this.each(function() {
			if( options ) {
				$.extend( settings, options );
			}

			if($(this).getTag()=='table') {
				$(this).find('>tbody > tr:odd, >tbody > tr:odd td,').addClass('odd');
				$(this).find('>tbody > tr:even, >tbody > tr:even td').addClass('even');
			} else {
				$(this).children(':odd').addClass('odd');
				$(this).children(':even').addClass('even');
			}
		});
	};
})(jQuery);



/**
 * Global application namespace.
 */
var APP = {
	settings: {
		language: 'en',
		paths   : {
			theme  : 'resources/themes/',
			plugins: 'resources/js/plugins/',
			skins  : 'skins/'
		},
		theme: {
			name: 'default',
			skin: ''
		},
		translation: {}
	}
};

/**
 * Erstes und letztes Element makieren
 *
 * @param m Mixed Selector oder das Element selbst
 * @param cF String Klassenname für erstes Kindelement
 * @param cL String Klassenname für letztes Kindelement
 *
 * @return /
 */
APP.markFirstLastChildren = function(s) {
	if(!s) {
		s = 'ul, dl';
	}

	$(s)
	.find('>:first').addClass('is-first').end()
	.find('>:last').addClass('is-last').end();
};

/**
 * Parse Opacity
 *
 * Transparenz automatisch per CSS-Klasse setzen.
 * <p class="set-opacity_{n}" />
 * n = 1-10 (0=0, 1=0.1, ..., 10=1)
 *
 * @param m Mixed Selector oder das Element selbst
 *
 * @return /
 */
APP.parseOpacity = function(m) {
	if(!m) {
		m = document.body;
	}

	for(var i=0; i<=10; i++) {
		$(m).find('.set-opacity_' + i).css('opacity', i/10);
	}
};

/**
 * Calendar
 *
 * @param m Mixed Selector oder Element selbst
 * @param p Object Kalenderparameter, einmal mit Key für 'calendar' und einmal für 'calendarRange' (Optionen analog jQuery UI)
 *
 * @return /
 */
APP.cal = [];
APP.calendar = function(m, p) {

	if(!m) {
		m = $(document.body).find('.append-calendar').not(".append-calendar[id$='_range']");
	}

	var settings = $.extend(true, {
		calendar: {
			dateFormat       : 'dd.mm.yy',
			minDate          : 0,
			selectOtherMonths: true,
			showAnim         : 'fadeIn',
			showOtherMonths  : true
		},
		calendarRange: {
			dateFormat    : 'dd.mm.yy',
			minDate       : 0,
			numberOfMonths: 1
		}
	}, p||{});

	var add_cal = function(id) {
		APP.cal[id] = $('#'+id).datepicker(settings.calendar);
	};

	var add_rangeCal = function(id, id_range) {

		APP.cal[id] = $('#'+id+', #'+id_range).datepicker($.extend(true, settings.calendarRange, {
			onSelect: function(selectedDate) {
				var option = this.id == id ? "minDate" : "maxDate";
				var instance = $(this).data("datepicker");
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				APP.cal[id].not(this).datepicker("option", option, date);
			}
		}));
	};

	if(m.length > 0) {

		m.each(function() {
			var id = $(this).attr('id'),
			id_range = id+'_range';
			if($('#'+id_range).length > 0) {
				add_rangeCal(id, id_range);
			} else {
				add_cal(id);
			}

		});

	}
};

/**
 * Mouseenter und -leave für Listen (ul > li)
 *
 * @param m Mixed Selector oder das Element selbst
 * @param p Object Parameter
 *
 * @return /
 */
APP.appendHover = function(m, p) {
	if(!m) {
		m = $(document.body).find('.append-hover').not(".append-hover[class~='hover']");
	}

	if(m.length > 0) {

		var settings = $.extend({
			classHover: 'hover',
			onHover   : $.noop(),
			onLeave   : $.noop()
		}, p||{});

		m.hover(function() {
			$(this).addClass(settings.classHover);

			if($.isFunction(settings.onHover)) {
				settings.onHover($(this));
			}
		}, function() {
			$(this).removeClass(settings.classHover);

			if($.isFunction(settings.onLeave)) {
				settings.onLeave($(this));
			}
		});

	}
};

/**
 * Tooltip
 *
 * @param m Mixed Selector oder das Element selbst
 * @param p Object Parameter
 *
 * @return /
 */
APP.appendTooltip = function(m, p) {
	var m = (!m) ? $('.tooltip') : $(m);

	if(m.length > 0) {

		var settings = $.extend({
			delay     : 0,
			extraClass: 'ttip',
			fixPNG    : true,
			left      : 15,
			opacity   : .7,
			showBody  : '::',
			showURL   : false,
			top       : -5,
			track     : true
		}, p||{});

		m.btooltip(settings);

	}
};


/**
 * Galerie initialisieren
 */
APP.gallery = function() {


	if($('.gallery').length > 0 && $('.gal-page_slides-item').length > 1) {

		var gal_can_slide = ($('.gallery').find('.gal-page').length > 1) ? true : false;
		var gal_first_info = null;

		// Events für den Textblock pro Galerieeintrag
		// -------------------------------------------

		$('.gallery .gal-content .gal-page').each(function() {
			// Info-block
			gal_first_info = $(this).find('.gal-page_info').css('opacity', 0).bind({
				'doHide': function(ev, cmd) {
					$(this).animate({
						opacity: 0
					}, 500, function() {
						var el = $(this).parent().find('.gal-page_slides .to-fade');
						if(el.length>0) {
							$(el).delay(1000).fadeTo(100, 0);
						}
					});
				},
				'doShow': function(ev, cmd) {
					$(this).animate({
						opacity: 1
					}, 500, function() {
						var el = $(this).parent().find('.gal-page_slides .to-fade');
						if(el.length>0) {
							$(el).delay(2000).fadeTo(500, 1);
						}
					});
				}
			});

			// Info-block
			$(this).find(".gal-page_slides .gal-page_slides-item:gt(1)").remove();
			$(this).find(".gal-page_slides .gal-page_slides-item:eq(1)").css('opacity', 0).addClass('to-fade');
		});

		// Hauptgalerie
		// ------------

		$('.gallery .gal-content').scrollable({
			circular  : true,
			easing    : 'easeInOutQuart',//'easeOutBounce',
			items     : '.gal-page',
//			keyboard  : 'static',
			mousewheel: false,
			next      : '.gal-next',
			onBeforeSeek: function() {
				var idx = this.getIndex(),
					it = this.getItems().eq(idx).find('.gal-page_info');
				$(it).trigger('doHide');
			},
			onSeek    : function() {
				var idx = this.getIndex(),
					it = this.getItems().eq(idx).find('.gal-page_info');

				$(it).trigger('doShow');
			},
			prev      : '.gal-prev',
			speed     : 800,
			vertical  : true
		}).navigator('.gal-nav').autoscroll({
			autoplay: true,
			interval: 5500,
			steps   : 1
		});
		var api_main_gallery = $('.gallery .gal-content').data('scrollable');

		// Init
		// ----

		if(gal_can_slide) {
			api_main_gallery.seekTo(0, 100);
		} else {

			if(gal_first_info) {
				api_main_gallery.stop();
				$(gal_first_info).trigger('doShow');
			}

		}

	}
};


APP.slideFooter = function()
{
	// add clickzone
	$('<div id="footer-click" title="Klicken Sie hier um die Sitemap zu öffnen oder zu schließen!"></div>').insertBefore('#footer')

	var footer_height	= $('#footer').height(),
		hide_pos		= -footer_height+40;

	// hide footer by default
	/*$('#footer').css({
		'top': hide_pos,
		'margin-bottom': hide_pos
	});*/

	// start slide in
	//$('#footer').delay(5000).animate({ 'top': 0 }, 1000);

	// click handler
	$('#footer-click').click(
		function()
		{
			var temp = ($('#footer').css('top') == '0px') ? hide_pos : 0;

			$('#footer').animate(
				{
					'margin-bottom': temp,
					'top': temp
				},
				1000
			);
		}
	);
}

/**
 * Main-Initialisierung.
 */
$(function() {
	//APP.settings = $.extend(true, APP.settings, APP_SETTINGS||{});

	$('a').live('click', function() { // fix border arround links
		$(this).blur();
	});

	APP.markFirstLastChildren(); // ? see function

	$( 'select.autosubmit' ).autoSubmit();



//	if($.browser.msie && $.browser.version.substr(0, 2) <= '7.') { // Navigation (Stupid MsIE 6)
//		APP.appendHover($('#MainNavi li'));
//	}



	$('#menu').superfish({
		hoverClass	: 'hovered',
		delay		: 200,
		animation	: {
			height : 'show'
		},
		speed		: 100,
		autoArrows	: false,
		dropShadows : false
	}).find('ul').bgIframe({
		opacity: false
	});

	APP.parseOpacity(); // ? see function

	APP.appendTooltip(); // ? see function


	var ttip_caption_items = $('span.iBlock-ttip-caption').filter(function() {
		return ($(this).find('.iBlock_Caption'));
	});

	if(ttip_caption_items.length>0) {
		$(document.body).append($('<div id="ttipCaption"><div class="ttip_caption-wrapper"><div class="ttip_caption-body">&nbsp;</div></div></div>'));

		$('span.iBlock-ttip-caption').filter(function() {
			return ($(this).find('.iBlock_Caption'));
		})
		.find('.tooltip').unbind().end()
		.tooltip({
			direction   : 'left',
			effect      : 'slide',
			onBeforeShow: function() {
				var c = this.getTrigger().find('.iBlock_Caption').html();
				this.getTip().find('.ttip_caption-body').html(c).end();
			},
			onHide: function() {
				this.getTip().find('.ttip_caption-body').empty();
			},
			offset     : [162, 40],
			opacity    : 0.9,
			position   : 'top right',
			slideOffset: 62,
			tip        : '#ttipCaption'
		});
	}

	// Bild vergrößern
	if($("a[rel='use-fb']").length > 0) {
		$("a[rel='use-fb']").fancybox({
//			'transitionIn'		: 'none',
//			'transitionOut'		: 'none',
//			'titlePosition' 	: 'over',
//			'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
//			    return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
//			}

			'centerOnScroll': true,
			'transitionIn'  : 'elastic',
			'transitionOut' : 'elastic',
			'speedIn'       : 600,
			'speedOut'      : 200,
//			'overlayColor'  : '#7f94bc',
			'overlayShow'   : false
//			'overlayOpacity': .9
		});
	}

	if($("a[rel='use-fb_youtube']").length > 0) {
		$("a[rel='use-fb_youtube']").fancybox({
			'centerOnScroll': true,
			'height'        : 413,
//			'overlayColor'  : '#7f94bc',
			'overlayShow'   : false,
			'speedIn'       : 600,
			'speedOut'      : 200,
			'titleShow'     : false,
			'transitionIn'  : 'elastic',
			'transitionOut' : 'elastic',
			'type'	      : 'iframe',
			'width'         : 550
		});
	}


	if($("a.use-iframe").length > 0) {
		$("a.use-iframe").each(function() {
			var rel     = $(this).attr('rel');
			var dWidth  = parseInt(rel.match(/width=[0-9]+/i)[0].replace('width=',''));
			var dHeight = parseInt(rel.match(/height=[0-9]+/i)[0].replace('height=',''));

			$(this).fancybox({
				width         : dWidth,
				height        : dHeight,
				padding       : 20,
				overlayOpacity: 0.7,
				overlayColor  : '#FFF',
				titleShow     : false,
				scrolling     : 'no',
				type	      : 'iframe'
			});
		});
	}
	if($("a.use-ajax").length > 0) {
		$("a.use-ajax").each(function() {
			var rel     = $(this).attr('rel');
			var dWidth  = parseInt(rel.match(/width=[0-9]+/i)[0].replace('width=',''));
			var dHeight = parseInt(rel.match(/height=[0-9]+/i)[0].replace('height=',''));

			$(this).fancybox({
				width         : dWidth,
				height        : dHeight,
				padding       : 20,
				overlayOpacity: 0.7,
				overlayColor  : '#FFF',
				titleShow     : false,
				scrolling     : 'yes',
				cyclic		  : 'cyclic',
				showNavArrows : false,
				type	      : 'ajax'
			});
		});
	}

	// Galerie initialisieren
	APP.gallery();
	// Teaser Tool
	if($('#sidebar-follow').length>0 && $('#content').length>0) {
		$('#sidebar-follow').scrollFollow({
			container: 'content',
			offset   :20
		});
	}

	// Kalender
	APP.calendar();

	// Suchformular - toggle value
	var searchform = $('#form_search'),
		searchinput = searchform.find('input#suchbegriff'),
		searchvalue = searchinput.val();

	searchinput.focus(function(){
		if ($(this).val() === searchvalue) $(this).val("");
	}).blur(function(){
		if ($(this).val() === '') $(this).val(searchvalue);
	});

	// Zebra tables
	$('table.tbl-zebra').each(function() {
		$(this).find('>tbody > tr:odd').addClass('odd');
		$(this).find('>tbody > tr:even').addClass('even');
	});


	// add footer animations
	APP.slideFooter();

});
