//global functions

/*
*	function to shorten the xml-blog-posts without cut off a part of an html tag
*/
function toggleBlogPost(){
	maxSize	= 700;
	postCount	= 0;
	$target = $('div.class-blog div.content-view-line div.class-blog-post div.attribute-body');

	//remove pictures
	$('div.class-blog div.content-view-line div.class-blog-post div.attribute-body div.class-image').remove(':has(img)');

	
	$target.each(function(){
		$post		= $(this);
		
		// post is to long
		if ($post.html().length > maxSize) {
		    //find the cut
			sum		= 0;
			$('p', $post).each(function(){
				$p		= $(this);
				html	= $p.html()
				size 	= html.length;
				
				if (sum > maxSize) {
					$p.remove();
				} else {
					if ((sum + size) > maxSize) {
						rest = (sum == 0) ? (maxSize) : (sum - size);
						$p.html(html.substring(0, rest) + "&nbsp;...");
					} 
				}
				sum += size;
			});
		}
		postCount++;
	});
}

function handleBlogComments(){
	$target = $('div.class-blog div.content-view-full div.class-blog-post div.attribute-comments');
	$target.data('status', 'empty');
	$form	= $('form', $target);

	// load the form for a new comment via ajax
	$form.submit(function(){
		 switch ($target.data("status")) {
		 	// first call
		 	case 'empty':
				$target.data("status", 'opened');
				$.post(
					$form.attr('action'),
					{
						ClassIdentifier 	: $('input[name="ClassIdentifier"]').val(),
						NodeID 				: $('input[name="NodeID"]').val(),
						ContentLanguageCode : $('input[name="ContentLanguageCode"]').val(),
						NewButton			: $('input[name="NewButton"]').val(),
						ajax				: true
					},
					//this function will be called to initialize the comment form
					function(data){
						// insert only the form, not the whole response
						$form =	$('div.class-comment form', $(data));
						$('#author', $form).prop('disabled', false); //bot protection
						$container	= $('<div>', {'class' : 'ajax-form'});
						$container.append($form);
						$target.before($container);
						//register actions on discarding
						$('input[name="DiscardButton"]', $container).click(function(){
							$container.slideUp(function(){
								$target.data('status', 'closed');
								$('input[type!="submit"]', $form).val('');
								$('textarea', $form).val('');
							});
							return false;
						});
						$container.slideDown();
					},
					'html'
				);	
				break;
			//second call
			case 'closed':
				$('div.ajax-form').slideDown();
				$target.data('status', 'opened');
				break;
			//opend -> close it
			default:
				return false;
				break;
		} 
		return false;
	});
	return false;
}

function wordpress(){

    var flag = false;
    var reg = /\bhttp:\/\/.+\.(de|com|eu)\b/;
    var address = prompt('Bitte geben Sie die Adresse des Blogs ein:', 'http://');

    while(address != null && !flag){    
        if(true == reg.test(address)){
            var content = $('.attribute-short > p').html(); 
            if(content == null){
                content = 'Interessanter Artikel  bei www.komm-mach-mint.de:'; 
            }
            var url = encodeURIComponent(location.href);    
            var title =  document.title.replace(/\s/g,'+');
            var aTitle = title.split('/');
            title = '+' + aTitle[0];


            var parameters = "/wp-admin/press-this.php?u=" + url + '&t=' + title + '&s=' + encodeURIComponent(content) + '&v=2'; 
         
            address = address + parameters;
            var w = window.open(address,"wpress","width=700, height=400, menubar=no");
            flag = true; 
        }else{
            address = prompt("Die eingegebene Adresse ist nicht gültig!\nBitte geben Sie eine korrekte Adresse eines  Wordpress-Blogs ein:", 'http://');
        }
    }
    return false;
}


function Paginator()
{
	var size = 12;
	var page = 0;
	var imageCount = $('.lightbox').length;

	this.getSize = function(){return size;}
	this.getPage = function(){return page;}
	this.getImageCount = function(){return imageCount;}

	this.incPage = function(){
		if(((page + 1)  * size) < imageCount){
			page++;
			return true;
		}
		return false;
	}	

	this.decPage = function(){
		if(page > 0){
			page--;
			return true;
		}
		return false;
	}
	
	this.showPaginator();
}

Paginator.prototype.next = function(){
	if(this.incPage()){
		this.showPage();	
	}
}

Paginator.prototype.prev = function(){
	if(this.decPage()){
		this.showPage();
	}
}

Paginator.prototype.showPage = function(){
	$('div.visible').removeClass('visible').addClass('hidden');
	var from = this.getPage() * this.getSize();
	if(from < 0){
		from = 0;
	}
	var end = from + 12;
	$("div.content-view-galleryline").slice(from, end).removeClass('hidden').addClass('visible');

	this.showPaginator();
}

Paginator.prototype.showPaginator = function(){
	if(this.getImageCount() > ((this.getPage() + 1) * this.getSize())){
		$('#fm_next').css('visibility','visible');
	}else{
		$('#fm_next').css('visibility','hidden');
	}
	if(this.getPage() > 0){
		$('#fm_prev').css('visibility', 'visible');
	}else{
		$('#fm_prev').css('visibility', 'hidden');

	}
}

function EventToggler()
{
	var settings = {
		handlerTarget : new Array(
			'div.content-view-line div.class-event h4 a',
			'a.show_details'
		)
	}

	this.$opened = null;
	
	this.init = function(){
		for(var i = 0; i < settings.handlerTarget.length; i++){
			$(settings.handlerTarget[i]).click(this.toggle);
		}
	}

	this.toggle	= function(){
		$this		= $(this);
		$parent		= $this.parents('div.class-event:first');
		$details	= $parent.children('div.event_description');

		if ($this.hasClass('show_details')){
			$link	= $this;
		}else{
			$link	= $parent.children('a.show_details');
		}
		if($link.hasClass('details_hidden')){
			$link.addClass('details_shown').removeClass('details_hidden');
			$details.slideDown(300);
			$link.text('Weniger...')
		}else{
			$link.addClass('details_hidden').removeClass('details_shown');
			$details.slideUp(300);
			$link.text('Mehr...')
		}
		return false;
	}
}


function registerFlashLayer(config)
{
	$trigger			= (config.target) ? $(config.target) : $('a.thickbox');
	config.height		= (config.height) ? config.height : 690;
	config.width		= (config.width) ? config.width : 1005;
	config.namespace	= 'flashlayer';

	$trigger.unbind();

	$win		= $('<div id="TB_window" style="width: ' + config.width + 'px; height:' + config.height + 'px; display: block;"><a title="Schließen" id="TB_ImageOff" href=""><iframe id="flashcontainer" src="' + config.url + '" style="height: 620px; width:990px;margin:15px 0 0 15px"></iframe></a><div id="TB_caption"><div id="TB_secondLine"></div></div><div id="TB_closeWindow"><a title="Schließen" id="TB_closeWindowButton" href="#"><img src="/extension/silver.project/design/silver.project/images/close.gif"></a></div></div>');
	$layer 	= $('<div id="TB_overlay" class="TB_overlayBG"></div>');

	$trigger.bind('click.' + config.namespace, function(event){
		event.preventDefault();

		$('body')	.append($layer)
					.append($win);
			
		$window	= $(window);
		offsetX	= ($window.width() - config.width) / 2;
		offsetY = ($window.height() - config.height) / 2;
		offsetX = (offsetX < 0) ? $window.width() - config.width : offsetX;
		offsetY = (offsetY < 0) ? $window.height() - config.height : offsetY;

		$('#TB_window')	.css('display', 'block')
						.css('top', offsetY)
						.css('left', offsetX);

		if (offsetX < 0 || offsetY < 0) {
			$('#TB_window')	.css('overflow', 'scroll');
		} else {
			$('#TB_window')	.css('overflow', 'hidden');
		}

		$layer.bind('click.' + config.namespace, function(event){
			$win.remove();
			$layer.remove();
		});

		//eventhandler for closing
		$('#TB_closeWindowButton').bind('click.' + config.namespace, function(){
			$win.remove();
			$layer.remove();
		});

		$window.bind('resize.' + config.namespace, function(){
			offsetX	= ($window.width() - config.width) / 2;
			offsetY = ($window.height() - config.height) / 2;
			offsetX = (offsetX < 0) ? $window.width() - config.width : offsetX;
			offsetY = (offsetY < 0) ? $window.height() - config.height : offsetY;
			
			$('#TB_window')	.css('top', offsetY)
							.css('left', offsetX)
			if (offsetX < 0 || offsetY < 0) {
				$('#TB_window')	.css('overflow', 'scroll');
			} else {
				$('#TB_window')	.css('overflow', 'hidden');
			}

		});

	});
}

$(function(){
		// eventListener for the imageOption
	$('div.imageOption > .thickbox ').click(function(){
		$(this).parent().children('input').attr('checked', true);
	});
	if(location.pathname == '/Service/Anfrage-MINT-Box'){
		
		/* 
			create the styles for the input fields */

		$('#termin_von').parents(':first').addClass('floatLeft');
		$('#termin_bis').parents(':first').addClass('floatLeft');
		$('#termin_bis').parents(':first').next().addClass('clearBoth');
		$('#termin_von').prev().css('width','250px');		
		$('#termin_bis').prev().css('width','auto');		

		// configure the datePicker
		$.dpText = {
			TEXT_PREV_YEAR		:	'Ein Jahr zurück blättern',
			TEXT_PREV_MONTH		:	'Einen Monat zurück blättern',
			TEXT_NEXT_YEAR		:	'Nächstes Jahr',
			TEXT_NEXT_MONTH		:	'Nächster Monat',
			TEXT_CLOSE			:	'Kalender schließen',
			TEXT_CHOOSE_DATE	:	'Kalender anzeigen'
		}
		Date.firstDayOfWeek = 1;
		Date.format = 'dd.mmm.yyyy';
		$(function()
		{
			$('#termin_von').datePicker()
			$('#termin_bis').datePicker()
		});
	}

	p = new Paginator();
	$('#fm_prev').click(function(){
		p.prev();
	});
	$('#fm_next').click(function(){
		p.next();
	});
/*	addLightboxEvent($('.lightbox > a'));*/
  $('.lightbox > a').lightBox({
        overlayBgColor: '#000000',
	    overlayOpacity: 0.75,
        imageBtnClose: '/extension/silver.project/design/silver.project/images/close.gif',
        imageLoading : '/extension/silver.project/design/silver.project/images/loading.gif',
        imageBtnPrev : '/extension/silver.project/design/silver.project/images/btnLeft.png',
        imageBtnNext : '/extension/silver.project/design/silver.project/images/btnRight.png',
        txtImage: 'Bild', 
	    txtOf: 'von'
    });

	// logger for social network
	$('#social_network a').click(function(){
		root = this;
		$.get('/urlwrapper/logger/social', {type : this.id}, function(){location.href=root.href});
		return false;
	});

	if(location.pathname == '/MINT-Jobboerse'){
			var $pic	= $('#maintop img');
			var text	= 'Bild für die MINT-Jobbörse';
			$pic.attr('src', '/extension/silver.project/design/silver.project/images/jobboerse.jpg').attr('alt', text).attr('title', text);
	}

	//initialize the event toggler
	var toggler = new EventToggler();
	toggler.init();
	$('div.content-view-infobox div.class-event h4 a').attr('href', 'http://www.komm-mach-mint.de/Termine');

	flashies	= {
		mintstyle : {
			pathname 	: /^\/MINT-Du\/Interaktiv\/MINT-Style\/?$/, 
			url			: 'http://mint-style.kompetenzz.net/index.php',	
			height		: null,
			width		: null,
			target		: null 
		},
		minttest : {
			pathname 	: /^\/MINT-Du\/Interaktiv\/MINT-Test\/?$/, 
			url			: 'http://www.komm-mach-mint.de/MintQuiz.html?KeepThis=true&',	
			height		: 695,
			width		: 1005,
			target		: null 
		}

	}
	
	for (entry in flashies) {
		if (flashies[entry].pathname.test(window.location.pathname)) {
			registerFlashLayer(flashies[entry]);
		}
	}

	if ($('hr.teaser').length > 0) {
		$('body').ezutils('oeteaser');
	}

	$('div#class-partnerbox div.attribute-media').partnerlogo();
});

