/**
 * @author stefan.schult
 * @id $Id: functions.js 687 2010-04-20 16:23:38Z stefan.schult $
 */
var isStartPage = false;
var startAnchor = '';
var pp = {};

pp.fbLike = {
	scrolling: 'no',
	frameborder: 0,
	allowTransparency:true,
	layout: 'button_count',
	show_faces: false,
	width: 100,
	height: 21,
	verb: 'like',
	font: 'arial',
	color: 'light'
};

var CONFIG = {
	BingMaps : {
		key : "At1arcwtPHvAHX67ccP1e9UDVYF4TUOWRThlvekIUY2ZTxDS7A6LbsA9PES1J85e"
	},
	Facebook : {
		key : "172578239443945",
		profileId: ""
	}
}

function init(fn) {
	try {
		$(fn);
	} catch(ex) {
	}

}

if($.html5forms != undefined)
	$.html5forms();

init(function() {

	$('body').addClass('js');
	$('body>div').removeClass('no-js');
	// Plugins
	try {
		$('input.preFilled').inpPrefilled();
	} catch (ex){}
});

init(function() {
	if ($('.images').length > 0) {
		$('body').append($('<div class="simple_overlay" id="gallery"><a class="prev">zurÃ¼ck</a><a class="next">vor</a><div class="info"></div><img class="progress" src="/fileadmin/layout/img/overlay/loading.gif" /></div>'));
		$('.images').each(function() {
			$(this).find('li:nth-child(4n)').next().addClass('bC');
			$(this).find('ul img').each(function() {
				$(this).css('margin-top', -$(this).height() / 2);
			});
			try {
				$(this).find('a').overlay({
					target: '#gallery',
					expose: '#f1f1f1'
				}).gallery({
					speed: 800,
					template: '<span>Bild ${index} von ${total}</span>'
				});
			} catch(ex) {
			}
		});
	}
});

init(function() {
	$('.contSitemapMod>ul>li:last-child').addClass('lastChild');
});

init(function() {
	$('.teaser-visual .iPpMod').each(function() {
		var href = $('a:first', this).attr('href');
		$(this).click(function() {
			location.href = href;
		});
	});
});

// Facebook - LikeItButton
$(function() {
	//mit sprechblase
	//$('div#facebookLikeIt').fbLike(encodeURIComponent(location.href), pp.fbLike);
});

// Adding Bingmaps
$(function() {
	var pins = [];
	try {
		$('.bingmaps').bingmaps({key: CONFIG.BingMaps.key, pins: pins});
	} catch (ex){}
});

//Facebook Likebox
$(function(){
	var likebox = $('.teaser-facebook-likebox');
	likebox.each(function(){
		var that = $(this),
		iThat = $('>div', that),
		background = iThat.attr('data-background'),
		hasBackground = (background != ''),
		href = iThat.attr('data-href'),
		hasHref= (href != ''),
		width = 299,
		fb_box = $('<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FWissenschaftsjahr%2F136885869703480&amp;width=' + width +'&amp;colorscheme=light&amp;show_faces=true&amp;stream=false&amp;header=false&amp;height=255&amp;timestamp=' + (new Date().getTime()) + '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:255px;" allowTransparency="true"></iframe>');
		if(hasBackground) {
			that.addClass('teaser-facebook-likebox-with-background');
			iThat.css('background-image', 'url(' + background + ')');
		}
		if(hasHref) {
			iThat.click(function(){
				location.href = href;
			});
		}
		iThat.append($(fb_box));

	});

});



init(function() {
	var firstSelected = -1;
	function getDisabled(p){
		var d = [];
		$('>ul li', p).each(function(i){
			if($(this).hasClass('disabled')){
				d.push(i);
			} else if(firstSelected == -1){
				firstSelected = i;
			}
		});
		return d;
	}
	$('.partner > div').each(function(){
		var partner = $(this);
	try {
		partner.tabs({
			disabled: getDisabled(partner),
			selected: firstSelected
		});
	} catch(ex){};
	});
});


init(function() {
	var defaultMaxLength = {
		events: [], // Array of events to be triggerd
		maxCharacters: 450, // Characters limit
		status:	true, // True to show status indicator bewlow the element
		statusClass: "status", // The class on the status div
		statusText: "Noch @value@ Zeichen", // The status text
		notificationClass: "notification",	// Will be added to the emement when maxlength is reached
		showAlert: false, // True to show a regular alert message
		alertText: "You have typed too many characters.", // Text in the alert message
		slider:	false // Use counter slider
	};
	$("#eventtitle").maxlength($.extend({}, defaultMaxLength, {maxCharacters: 60}));
	$("#shortdesc").maxlength($.extend({}, defaultMaxLength, {maxCharacters: 300}));
	$("#frage").maxlength($.extend({}, defaultMaxLength, {maxCharacters: 130}));
	$("#longdesc, #event_kostentext").maxlength($.extend({}, defaultMaxLength, {maxCharacters: 2500}));
});

init(function() {
	function showSubFields() {
		var name = $(this).attr('id');
		var subs = $('.sub-' + name);
		if (this.checked) {
			subs.addClass("inv");
		} else {
			subs.removeClass("inv");
		}
	}

	$(".subFieldMod input[type=checkbox]").each(function() {
		var proxy = $.proxy(showSubFields, this);
		$(this).click(showSubFields);
		proxy();
	})
});

init(function() {
	$('.teaser-list .iPpMod').each(function(i) {
		$('li', this).each(function(j){
			j = j+1;
			$('span', this).addClass('txt');
			$(this).prepend('<span class="digit">' + j + '.</span>');

		});
	})
});

init(function() {
	$('.teaser-image-text .iPpMod').each(function(i) {
		var img = $('.image-container', this);
		var lnk = $('h3 a:first', this);
		var c = 'onHover';
		lnk.hover(function(){
			img.addClass(c);
		}, function(){
			img.removeClass(c)
		});
		img.click(function(){
			if(lnk.attr('href').search('/^http:///')){
				location.href = lnk.attr('href');
			}else {
				location.href = $('head base').attr('href') + lnk.attr('href');
			}
		});
	})
});

init(function() {
	$('.teaser-coverflow .iPpMod').each(function(i) {
		var current, liWidth, maxViewAble, step, max;
		current = 0;
		function refresh() {
			liWidth = lis.width();
			maxViewAble = $('>div', that).width() / liWidth;
			step = maxViewAble * liWidth;
			max = Math.ceil(lis.length / maxViewAble);
		}

		var that = this;
		var ul = $('ul', that);
		var lis = $('li', ul);
		var base = $('head base').attr('href');
		refresh();
		lis.each(function(i){
			var href = $('a', this).attr('href');
			var target = $('a', this).attr('target');
            console.debug(target);
			$('.image-context', $(this)).click(function(){
                if (href.substring(0, 7) == 'http://') {
                    if (target == '_blank') {
                        var new_window = window.open(href);
                    }
                    else {
                        location.href = href;
                    }
                }
                else {
                    if (target == '_blank') {
                        var new_window = window.open(base + href);
                    }
                    else {
                        location.href = base + href;
                    }
                }
			});
		});
		if (max > 1) {
//			var top = $(lis).height() - $('.text-container', lis).height();
			var navBar = $('<ul class="navBar"><li class="next"><a href="javascript:void(0)" title="vor"><span>vor</span></a></li><li class="prev"><a href="javascript:void(0)" title="zurÃ¼ck"><span>zurÃ¼ck</span></a></li></ul>');
//			navBar.css('top', top+'px');
			$(that).append(navBar);
			var a = $('a', navBar);
			$(a[0]).click(function() {
				refresh();
				current++;
				if (current < max) {
					ul.animate({left: '-=' + step}, 350);
				} else {
					ul.animate({left: '0'}, 200 * max);
					current = 0;
				}
			});
			$(a[1]).click(function() {
				refresh();
				current--;
				if (current > 0) {
					ul.animate({left: '+=' + step}, 350);
				} else {
					ul.animate({left: '-' + ((max - 1) * step)}, 200 * max);
					current = max;
				}
			});
		}
	});
});


function replaceURLWithHTMLLinks(text) {
	var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	return text.replace(exp, '<a target="_blank" class="external-link" href="$1">$1</a>');
}

//flash container
init(function() {
	var defaultParams = {
		quality: 'high',
		allowscriptaccess: 'sameDomain',
		allowfullscreen: 'true',
		scale: 'noscale',
		wmode: 'transparent'
	};
	var ID = {};
	(function(context) {
		var id = 0;

		context.next = function() {
			return id++;
		};

		context.current = function() {
			return id;
		};

		context.reset = function() {
			id = 0;
		}
	})(ID);
	var defaultAttributes = {
		align: "left"
	};

	$('.article-flash').each(function(i) {
		var id = 'article-flash-' + ID.next();
		$('.iPpMod', this).attr('id', id);
		$('span', this).remove();
		var flash_source = $(this).attr('data-flashfile'),
		width = ($(this).attr('data-width') != '') ? $(this).attr('data-width') : 580,
		height = ($(this).attr('data-height') != '') ? $(this).attr('data-height') : 200,
		flashvars = ($(this).attr('data-flashvars') != '') ? $.parseJSON($(this).attr('data-flashvars')) : null ,
		params = $.extend( {}, defaultParams),
		attributes = $.extend( {}, defaultAttributes, {name: id + '-obj', id: id + '-obj'});
		console.debug(flashvars, params, attributes);
		console.debug(flash_source, width, height);
		swfobject.embedSWF(flash_source, id, width, height, "9.0.0", '../swf/expressInstall.swf', flashvars, params);
	});
});

//youtube video
init(function() {
	$('.article-youtube').each(function(i) {
		var id = 'article-youtube-' + i;
		$('.iPpMod', this).attr('id', id);
		$('span', this).remove();
		var video_source = $(this).attr('data-youtube'),
		style = ($(this).attr('data-youtube-style') != '') ? $(this).attr('data-youtube-style') : 'green';
		$('#' + id).tubeplayer({
			width: 580, // the width of the player
			allowFullScreen: "true", // true by default, allow user to go full screen
			initialVideo: video_source, // the video that is loaded into the player
			playerID: id + '-player', // the ID of the embedded youtube player
			preferredQuality: "default",// preferred quality: default, small, medium, large, hd720
			onPlay: function(id) {
			}, // after the play method is called
			onPause: function() {
			}, // after the pause method is called
			onStop: function() {
			}, // after the player is stopped
			onSeek: function(time) {
			}, // after the video has been seeked to a defined point
			onMute: function() {
			}, // after the player is muted
			onUnMute: function() {
			} // after the player is unmuted
			,style: style
		});
	});
});

init(function() {
	if ($('#twitterRss').length) {
		var content = $('<div />');
		$('#twitterRss').prepend(content);
		$.ajax({
			type: "GET",
			cache: false,
			url: "/fileadmin/layout/js/twitter.php",
			success: function(xml) {
				content.append($(xml));
			}
		});

	}
});

