
    var $jq = jQuery.noConflict();
   
     // Use jQuery via jQuery(...)  
    
    jQuery(document).ready(function(){
    	
    	// Wildcardselector so that milkbox requests are substituted by colorbox
    	jQuery('a[rel*="milkbox"]').colorbox({
			current: "{current} / {total}",
			// Min width hack can be found on GIT (https://github.com/jackmoore/colorbox/issues?state=open)
			minWidth: 450,
			// Overlay clicks don't close the colorbox
			overlayClose: false,
			onLoad: function(){
				// Fixes tweening issues in Chrome
				jQuery('#cboxClose').css({'display':'none'});
			},
			copyright: function(){
				// Creates the copyright informations and the caption
					jQuery('#cbCopyright').remove();
					jQuery('#cboxTitle').css({'display':'block'});
					var copyright = jQuery('<div>').attr('id','cbCopyright').css({'display':'none'});;
					jQuery('#cboxContent').append(copyright);
					jQuery('#cbCopyright').html(jQuery(this).next(".hidden").html());
			},
			onComplete: function (){
				
				// Fixes tweening issues in Chrome
				jQuery('#cboxClose').css({'display':'block'});
				var hrefArray = jQuery(this).attr('href').substr(7).split('/');
				if(hrefArray[0] == "img.youtube.com"){
					//div[id*="video"] 
					var youtube = jQuery(this).parent().parent().find('div[id*="video"] object').clone();
					jQuery('#cboxLoadedContent').html(youtube).css({'background':'none'});
					jQuery.colorbox.resize({'innerWidth':524,'innerHeight':320});
				}
				jQuery('#cbCopyright').fadeIn('slow');
			}
		});
    	
    	jQuery('a[rel*="milkbox[comm"],a[rel*="milkbox[gall2"]').colorbox({
    		inline: true,
    		href: '#captcha_formfield',
			// Min width hack can be found on GIT (https://github.com/jackmoore/colorbox/issues?state=open)
			minWidth: 450,
			// Overlay clicks don't close the colorbox
			overlayClose: false,
			onLoad: function(){
				// Fixes tweening issues in Chrome
				jQuery('#cboxClose').css({'display':'none'});
				jQuery('#captcha_formfield').css({'display':'block'});
			},
			onComplete: function (){
				// Fixes tweening issues in Chrome
				jQuery('#cboxClose').css({'display':'block'});
				jQuery('#cboxTitle').css({'display':'none'});
				jQuery('#cboxLoadedContent').css({'background':'#FAF8F9'});
				jQuery('#cboxWrapper').css({'height':'340px'});
			},
			onCleanup: function(){
				jQuery('#captcha_formfield').css({'display':'none'});
				jQuery('#cboxTitle').css({'display':'block'});
			}
    	});
    	// Initialization of image carousel
    	jQuery("#container_slider").jCarouselLite({
    	    btnNext: "#slider_next",
    	    btnPrev: "#slider_prev",
    	    visible: 5,
    	    speed: 200,
    	    circular: false
    	});
    	
    	removeGalleryNav();
    	
    	jQuery("a[title*='Print']").click(function(){
    		window.print();
    		return false;
    	});
    	
    	// Rating form disable
    	if(jQuery("#ratechecked[rel='1']").length ){
    		jQuery('#inno-rating input').attr("disabled", true);
    		jQuery("input[name*='user_rating[submit_button]']").remove();
    		var loc = jQuery('#ratebackurl').val().toString();
    		window.location = loc;
    	}else{
    		jQuery('#inno-rating input').removeAttr("disabled");
    	}
    	
    	// Initialize sharing buttons in lists
    	initializeSocialMedia();
    	// Enables flapping of related content boxes
    	flapBoxes();
    	// Checks for cookiestring which boxes should be flapped
    	checkBoxStatus();
    	// Clear page browser input field on click
    	
    	// Pagebrowser JS
    	var currentPage = jQuery('.page_browse input.page').attr("value");
    	var maxPage = jQuery('.page_browse span.maxPage').html();
    	
    	jQuery('.page_browse input.page').focus(function(){
    		jQuery(this).attr("value","");
    	});
    	
    	jQuery('.page_browse input.page').focusout(function(){
    		//console.log(jQuery(this).attr("value"), maxPage);
    		if(jQuery(this).attr("value")=="" || isNaN(jQuery(this).attr("value"))== true || parseFloat(jQuery(this).attr("value")) > parseFloat(maxPage))
    		{
    			jQuery(this).attr("value", currentPage);    		
    		}	
    	});
    	
    	jQuery('form.pageBrowser').keydown(function(event){
    		if(event.keyCode == '13'){
	    		var page = jQuery(this).find('.page_browse input.page').attr("value");
	    		if(parseFloat(page) > parseFloat(maxPage))
	    		{
	    			page = maxPage;    		
	    		}
	    		
	    		if(parseFloat(page) < 0)
	    		{
	    			page = 1;
	    		}
	    		var action = jQuery(this).attr("action");
	    		action = action.replace("PBID", page);
	    		jQuery(this).attr("action", action);
	    		jQuery(this).submit();
	    		
	    		return false;
    		}
    	});
    	
    	/**jQuery( "#slider_inno" ).slider({
			range: true,
			min: 0,
			max: 10,
			values: [ 1, 10 ],
			slide: function( event, ui ) {
				jQuery( "#amount" ).val( "jQuery$" + ui.values[ 0 ] + " - jQuery" + ui.values[ 1 ] );
			}
		});
    	jQuery( "#amount" ).val( "jQuery" + jQuery( "#slider-range" ).slider( "values", 0 ) +
			" - jQuery" + jQuery( "#slider-range" ).slider( "values", 1 ) );
    	**/
    	
    	
     });
     
     // Use Prototype with $(...), etc.
  

var inno_start = 1;
var inno_end = 10;
var markt_start = 2010;
var markt_end = 2020;
var user_rating = 1;

window.addEvent('domready', function() {	
	
	/* ######## AUTOCOMPLETER ######## */
	
	// tags for offline mode
	var tokens = ['.net', '2008', '3d', 'advertising', 'ajax', 'appengine', 'apple', 'architecture', 'Art', 'article', 'articles', 'audio', 'blog', 'blogging', 'blogs', 'books', 'business', 'china', 'community', 'computer', 'cooking', 'cool', 'css', 'culture', 'design', 'development', 'diy', 'download', 'education', 'english', 'environment', 'fashion', 'fic', 'film', 'finance', 'firefox', 'flash', 'flex', 'flickr', 'fonts', 'food', 'free', 'freeware', 'fun', 'funny', 'gallery', 'games', 'generator', 'git', 'google', 'government', 'graphics', 'green', 'hardware', 'health', 'history', 'home', 'howto', 'humor', 'illustration', 'imported', 'inspiration', 'interactive', 'internet', 'java', 'javascript', 'job', 'jobs', 'language', 'law', 'library', 'linux', 'mac', 'maps', 'marketing', 'math', 'media', 'microsoft', 'mobile', 'money', 'mp3', 'music', 'news', 'online', 'opensource', 'osx', 'photo', 'photography', 'photos', 'photoshop', 'php', 'politics', 'portfolio', 'productivity', 'programming', 'python', 'rails', 'recipe', 'recipes', 'reference', 'research', 'resources', 'ruby', 'school', 'science', 'search', 'security', 'seo', 'sga', 'shopping', 'slash', 'social', 'software', 'statistics', 'teaching', 'tech', 'technology', 'tips', 'todo', 'tools', 'toread', 'travel', 'tutorial', 'tutorials', 'tv', 'twitter', 'typography', 'ubuntu', 'video', 'visualization', 'web', 'web2.0', 'webdesign', 'webdev', 'wiki', 'windows', 'wordpress', 'work', 'writing', 'youtube', 'degerli', 'is', 'modeli', 'anlayisiyla', 'temsilcisi', 'bulundugu', 'sasdasde', 'gasdr4g', 'Sasd3fg54', 'Iasd3sOr ', 'siyla'];
	
	// add autocompleter to tags
	try {
		// add autocompleter
		$$('.input_new_tag').each(function(item) {
			new Autocompleter.Request.JSON(item.id, '/index.php?id=95', {
				'indicatorClass': 'autocompleter-loading',
				'minLength': 2,
				'multiple': true
			});
		}); 
	} catch(error) {
		//console.debug(error);
	}
	
	// add autocompleter to search
	try {
		// get search_field
		var search_field = null;
		search_field = $('search_main_term');
		
		// check search_field
		if(search_field != null) {
			// add autocompleter
			new Autocompleter.Request.JSON(search_field, '/index.php?id=95', {
				'indicatorClass': 'autocompleter-loading',
				'minLength': 2
			}); 
		}
	} catch(error) {
		//console.debug(error);
	}
	
/* ######## TOGGLE WIDGETS ######## */
	
	// status for tags
	var status_tag = {
		'true': 'WENIGER',
		'false': 'MEHR'
	};
	
	// status for reply
	var status_reply = {
		'true': 'ABBRECHEN',
		'false': 'ANTWORTEN'
	};
	
	// status for new comment
	var status_reply_new = {
		'true': 'ABBRECHEN',
		'false': 'NEUER KOMMENTAR'
	};
	
	// for each toggleNest (content)
	try {
		$$('.rgaccord1-nest').each(function(item) {
			// get content
			var content = null;
			content = item.getElement('.rgaccord1-content');
			
			// check content
			if(content != null) {
				// add FxSlide
				var thisSlider = new Fx.Slide( content, { duration: 1000, transition: Fx.Transitions.Pow.easeOut } );
			}
			
			// get toggle
			var toggle = null;
			var prevToggle = null;
			var nextToggle = null;
			
			toggle = item.getElement('.rgaccord1-toggle');
			// grabs the thumb img as object
			prevToggle = toggle.getPrevious();
			nextToggle = toggle.getNext(['div img']);
			
			// check toggle
			if(toggle != null ) {
				// display or not?
				if(toggle.hasClass('act') != true) {
					thisSlider.hide();
				}
				
				// add toggle
				toggle.addEvent('click', function(e) {
					e.stop();
					thisSlider.toggle(); 
				});

				// add toggle
				if(prevToggle != null ){
					prevToggle.addEvent('click', function(f) {
						f.stop();
						thisSlider.toggle(); 
					});
				}
				// add toggle
				if(nextToggle != null ){
					nextToggle.setStyle('cursor','pointer');
					nextToggle.addEvent('click', function(g) {
						g.stop();
						thisSlider.toggle(); 
					});
				}
			
				// add complete
				thisSlider.addEvent('complete', function() {
					// add the act class
					if( toggle.hasClass('act') ) {
						toggle.removeClass('act');
					} else {
						toggle.addClass('act');
					}
				});
			}
		});
	} catch(error) {
		//console.debug(error);
	}
	
	// for each widget
//	try {
//		$$('.widget').each(function(item) {
//			// searchID for slider
//			var searchID = item.id;
//			
//			// get content
//			var content = null;
//			content = item.getElement('.widget-content');
//			
//			// check content
//			if(content != null) {
//				// add FxSlide
//				var thisSlider = new Fx.Slide( content, { duration: 500 } );
//			}
//			
//			// get parent --> hack for IE!!
//			var parent = null;
//			parent = item.getElement('.widget-toggle').parentNode;
//			
//			/*
//			// Weiche f�r IE7 CSS Fehler
//			if(parent != null) {
//				if(parent.attributes['class'].value == 'inner_wrapper') {
//					parent = item.getElement('.widget-toggle').parentNode.parentNode;
//				}
//			}
//			*/
//			
//			// check parent and attributes
//			if(parent != null) {
//				// display or not?
//				if(parent.attributes['class'].value != 'active') {
//					thisSlider.hide();
//				}
//			}
//			
//			// get toggle
//			var toggle = null;
//			toggle = item.getElement('.widget-toggle');
//			
//			// check toggle
//			if(toggle != null) {
//				// slider for search
//				var bg_slider_inno = null;
//				var bg_slider_markt = null;
//				
//				// fade for seach slider
//				try {
//					// get slider
//					bg_slider_inno = item.getElementById('bg_slider_inno');
//					bg_slider_markt = item.getElementById('bg_slider_markt');
//					
//					// add reveal
//					if(bg_slider_inno != null) {
//						bg_slider_inno_reveal = new Fx.Reveal( bg_slider_inno, { duration: 500 } ).toggle();
//					}
//					
//					// add reveal
//					if(bg_slider_inno != null) {
//						bg_slider_markt_reveal = new Fx.Reveal( bg_slider_markt, { duration: 500 } ).toggle();
//					
//					}
//					
//					// hide when inactive
//					if(parent.attributes['class'].value == 'inactive' && searchID == 'search_main_filter') {
//						bg_slider_inno_reveal.dissolve();
//						bg_slider_markt_reveal.dissolve();
//					} else if(parent.attributes['class'].value == 'active' && searchID == 'search_main_filter') {
//						bg_slider_inno_reveal.reveal();
//						bg_slider_markt_reveal.reveal();
//					}
//				} catch(error) {
//					//console.debug(error);
//				}
//				
//				// add toggle
//				toggle.addEvent('click', function(e) {
//					if(searchID == 'search_main_filter') {
//						bg_slider_inno_reveal.toggle();
//						bg_slider_markt_reveal.toggle();
//					}
//					// toggle
//					e.stop();
//					thisSlider.toggle(); 
//				});
//
//				// add complete
//				thisSlider.addEvent('complete', function() {
//					// check attributes
//					if(parent != null) {
//						// set class
//						if(parent.attributes['class'].value == 'active') {
//							parent.attributes['class'].value = 'inactive';
//						} else {
//							parent.attributes['class'].value = 'active';
//						}
//					}
//				});
//			}
//		});
//	} catch(error) {
//		alert(error);
//		//console.debug(error);
//	}
	
	// Tags
	try {
		$$('.tag-nest').each(function(item) {
			// get content
			var content = null;
			content = item.getElement('.tag-content');
			
			// check content
			if(content != null) {
				// add FxSlide
				var thisSlider = new Fx.Slide( content, { duration: 800, transition: Fx.Transitions.Pow.easeOut } );
			}
			
			// get toggle
			var toggle = null;
			toggle = item.getElement('.tag-toggle');
			
			// check toggle
			if(toggle != null) {
				// display or not?
				if(toggle.firstChild.nodeValue == 'MEHR') {
					thisSlider.hide();
				}
				
				// add toggle		
				toggle.addEvent('click', function(e) {
					e.stop();
					thisSlider.toggle(); 
				});
			
				// add complete
				thisSlider.addEvent('complete', function() {
					// toggle status
					toggle.innerHTML=status_tag[thisSlider.open];
				});
			}
		});
	} catch(error) {
		//console.debug(error);
	}

	// Comments
	try {
		$$('.comments-nest').each(function(item) {
			// get content
			var content = null;
			content = item.getElement('.comments-content');
			
			// check content
			if(content != null) {
				// add FxSlide
				var thisSlider = new Fx.Slide( content, { duration: 700, transition: Fx.Transitions.Pow.easeOut } );
			}
			
			// get reply
			var reply = null;
			reply = item.getElement('.comments_reply');
			
			// check reply
			if( reply != null && item.hasClass('reply-nest') ) {
				// set duration
				if(reply.firstChild.nodeValue == 'ANTWORTEN') {
					thisSlider.options.duration = 700;
				} else {
					thisSlider.options.duration = 1000;
				}
			}
			
			//get toggle
			var toggle = null;
			toggle = item.getElement('.comments-toggle');
			
			// check toggle
			if(toggle != null) {
				// display or not?
				if(toggle.hasClass('act') != true) {
					thisSlider.hide();
				}
				
				// add toggle
				toggle.addEvent('click', function(e) {
					e.stop();
					thisSlider.toggle(); 
				});
				
				// add complete
				thisSlider.addEvent('complete', function() {
					// add the act class
					if( toggle.hasClass('act') ) {
						toggle.removeClass('act');
					} else {
						toggle.addClass('act');
					}
					
					// set duration
					if( reply != null && item.hasClass('reply-nest') ) {
						if(reply.firstChild.nodeValue == 'ANTWORTEN') {
							thisSlider.options.duration = 700;
						} else {
							thisSlider.options.duration = 1000;
						}
					}
				});
			}
		});
	} catch(error) {
		//console.debug(error);
	}
	
	// Reply Comment
	try {
		$$('.reply-nest').each(function(item) {
			// get container
			var container = null;
			container = item.getElement('.reply_container');
			
			// check container
			if(container != null) {
				// add FxSlide
				var thisSlider = new Fx.Slide( container, { duration: 700, transition: Fx.Transitions.Pow.easeOut } );
			}
			
			// get reply
			var reply = null;
			reply = item.getElement('.comments_reply');
			
			// check reply
			if(reply != null) {
				// display or not?
				if(reply.firstChild.nodeValue == 'ANTWORTEN') {
					thisSlider.hide();
				}
				
				// add toggle
				reply.addEvent('click', function(e) {
					e.stop();
					thisSlider.toggle(); 
				});
				
				// add complete
				thisSlider.addEvent('complete', function() {
					// toggle status
					reply.innerHTML=status_reply[thisSlider.open];
				});
			}
		}); 
	} catch(error) {
		//console.debug(error);
	}

	// New Comment
	try {
		$$('#user_comment').each(function(item) {
			// get container
			var container = null;
			container = item.getElement('.comment_new-content');
			
			// check container
			if(container != null) {
				// add FxSlide
				var thisSlider = new Fx.Slide( container, { duration: 800, transition: Fx.Transitions.Pow.easeOut } );
			}
			
			// get reply
			var reply = null;
			reply = item.getElement('.comment_new');
			
			// check reply
			if(reply != null) {
				// display or not?
				if(reply.firstChild.nodeValue == 'NEUER KOMMENTAR') {
					thisSlider.hide();
				}
				
				// add toggle
				reply.addEvent('click', function(e) {
					e.stop();
					thisSlider.toggle(); 
				});
				
				// add complete
				thisSlider.addEvent('complete', function() {
					// toggle status
					reply.innerHTML=status_reply_new[thisSlider.open];
				});
			}
		}); 
	} catch(error) {
		//console.debug(error);
	}
	

	
	/* ######## SILDER SEARCH ######## */
	
	// Silder für Innovationsgrad
	var slider_inno = new Slider($('slider_inno'), $('slider_inno_minKnob'), $('bg_slider_inno'), {
		start: 1,
		end: 10,
		offset: 0,
		knobheight: 24,
		knobwidth: 24,
		snap: true,
		numsteps: 9,
		onChange: function(pos) {
			$('tx_innovisions_pi1[innovationgrad_min]').value=pos.minpos;
			$('tx_innovisions_pi1[innovationgrad_max]').value=pos.maxpos;
		}
	}, $('slider_inno_maxKnob')).setMin(inno_start).setMax(inno_end);
	
	// Silder für Marktreife
	$('marktreife_min').innerHTML=markt_start;
	$('marktreife_max').innerHTML=markt_end;
	
	var slider_markt = new Slider($('slider_markt'), $('slider_markt_minKnob'), $('bg_slider_markt'), {
		start: 2010,
		end: 2020,
		offset: 0,
		knobheight: 24,
		knobwidth: 24,
		snap: true,
		numsteps: 9,
		onChange: function(pos) {
			$('tx_innovisions_pi1[marktreife_min]').value=pos.minpos;
			$('tx_innovisions_pi1[marktreife_max]').value=pos.maxpos;
		}
	}, $('slider_markt_maxKnob')).setMin(markt_start).setMax(markt_end);
	
	// Silder f�r User-Rating
	var slider_rating = new Slider($('slider_rating'), $('slider_rating_knob'), $('bg_slider_rating'), {
		start: 1,
		end: 3,
		offset: 0,
		knobheight: 24,
		knobwidth: 26,
		snap: true, 
		numsteps: 2,
		onChange: function(pos){
			$('tx_innovisions_pi1[bewertung_type]').value=pos;
		}
	}, null).setMin(user_rating); 
	$('tx_innovisions_pi1[bewertung_type]').value=user_rating;
	
	// Blendet alle Tags in der Tagcloud aus die über die Logogrenze floaten würden
	clearTags();
	
	$$('.addTag').addEvent('click', function(){
		$(this).getParent().send();
		var id = $(this).get('id');
		
		compareTags(id);
		
		return false;
	});
	
	
	$$('.input_new_tag').addEvent('keydown', function(event){
			if(event.key=="enter"){
				$(this).getParent().send();
				var id = $(this).get('id').split('_').pop();
				compareTags(id);
				return false;
			}
	});
	
});
function compareTags(id){
	
	var tags = $$('#tagging_'+id+' li a').get('html');
	var newtag = $$('#content_'+id).get('value').toString();
	
	var newTags = new Array();
	var newTagsC = new Array();
	newtagArray = newtag.split(", ");
	
	for(i=0;i<tags.length;i++){
		for(j=0;j<newtagArray.length;j++){
			if(tags[i]==newtagArray[j]){
				delete newtagArray[j];
			}					
		}			
	}
	for(i=0;i<newtagArray.length;i++){
		if(newtagArray[i] != undefined){
			var last = $$('#tagging_'+id+' .tag-content li:last-child a');
			var href = last.get('href').toString();
			href = href.split("?");
			//console.log(href);
			var parent = $$('#tagging_'+id+' .tag-content ul');
			var clone = new Element('li');
			var cloneA = new Element ('a',
					{
						href: href[0]+'?search='+encodeURI(newtagArray[i]),
						html: newtagArray[i],
						style: 'font-weight:bold'
					}
			);
			if(ltrim(newtagArray[i], " ")!=""){
				clone.adopt(cloneA);
				parent.adopt(clone);
			}
		}
	}
	//console.log(newtagArray);
	
}
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function clearTags(){
	var tags = $$('div.tagcloud a');
	
	tags.each(function(item){
		var itemPosition = item.offsetTop + item.offsetHeight;
		var parentPosition = $('header_logo').offsetHeight + $('header_logo').offsetTop;
		// console.log('IP:'+itemPosition);
		// console.log('PP:'+parentPosition);
		if(itemPosition > parentPosition){
			item.setStyle("display", "none");			
		}
		
	});	
}
// check radiobutton
function checkRadio(radioObj) {
	if(!radioObj) {
		return;
	} else {
		var node = document.getElementById(radioObj.name);
		var headline = node.getElementsByTagName("h3");
		
		for(var i=0; i < headline.length; i++) {
			if(headline[i].hasClass('act') != true) {
				headline[i].addClass('act');
			}
		}
	}
}

// reset radiobutton
function resetRadio(formObj) {
	if(!formObj) {
		return;
	} else {
		var headline = formObj.getElementsByTagName("h3");
		
		for(var i=0; i < headline.length; i++) {
			if( headline[i].hasClass('act') ) {
				headline[i].removeClass('act') ;
			}
		}
	}
}

// Suchformular samt Tags
var urlFormFulltext = '/meta-seiten/suche/';
var urlFormTag = '/index.php?id=95';
var bufferConditon = new Array();

var validForm = false;
function showFullTextSearch(refElement){
	
	$('search_main_filter').setStyle('display','none');
	//var parent = refElement.getParent();
	var parent = refElement.parentNode;
	parent.setAttribute('id', 'search_switch_text_act');
	$('search_switch_tag_act').setAttribute('id', 'search_switch_tag');
	//$('searchtagstab_content').setStyle('display','none');
	//$('searchfulltexttab_content').setStyle('display','');
	$('search_main_form').setAttribute('action', urlFormFulltext);
	$('search_main_temp').setAttribute('name', 'tx_indexedsearch[sword]');
}
function showTagSearch(refElement){
	$('search_main_filter').setStyle('display','');
	//var parent = refElement.getParent();
	var parent = refElement.parentNode;
	parent.setAttribute('id', 'search_switch_tag_act');
	$('search_switch_text_act').setAttribute('id', 'search_switch_text');
	$('search_main_form').setAttribute('action', urlFormTag);
	$('search_main_term').setAttribute('name', 'tx_innovisions_pi1[keywords]');
}
document.searchKeywords = null;
lang = new Array();

function reGenerateKeywords(condition, nodeIndex){
	if(condition!=null & nodeIndex!=null){
		document.searchKeywords[nodeIndex]['logicalOperator'] = condition;
	}
	var txTag = null;
	txTag = $('search_main_term');
	txTag.value = '';
	var keyworsArray = document.searchKeywords.slice(0);
	var localIndexNode=0;
	while(keyworsArray.length>0){
		var node = keyworsArray.pop();
		if( !(node['value'] === undefined) && node['value'] != ''){	
			if(!(node['logicalOperator'] === undefined)){
				txTag.value = txTag.value + ' ' + node['logicalOperator'] + ' '  ;
			}
			txTag.value = txTag.value + node['value'];
		}
	}
	$('search_main_temp').value = txTag.value.replace(/((?:^|\s)(oder)(?=\s|$))|((?:^|\s)(or)(?=\s|$))/gi, "|")
	$('search_main_temp').value = $('search_main_temp').value.replace(/((?:^|\s)(und)(?=\s|$))|((?:^|\s)(and)(?=\s|$))/gi, "+")
	 
}
function deleteNodeRel(nodeId, idCond){
	var relDiv = $('search_main_relation');
	var last = null;
	last = relDiv.getLast('div');
	if(last!=null){
		last.destroy();
	}
}
var i = 0;
function onAddTag(e){
	if( typeof(e) == "undefined") return;
	$jq(function($) {
		
	
	var tagsDiv = null;
	tagsDiv = $('#search_main_tags');
	var relDiv = $('#search_main_relation');
	//console.log(tagsDiv);
	if(tagsDiv != null){
		
		//var txTag = null;
		var txTag = $('#search_main_term');
		//console.log($('#search_main_term'));			
		var evt = e || window.event;
		
		if(evt.keyCode == 13){
			//tagsDiv.innerHTML ='';
			//relDiv.innerHTML ='';
			//console.log(txTag);
			var searchKeywords = miniParser($jq.trim(txTag.val()));
			//document.searchKeywords = searchKeywords.slice(0);
			
			var idCond = 'cond' + new Date().getTime();
			var tagsCount = tagsDiv.children('div').length;
			var logicalCount = relDiv.children('div').length;
			//console.log('sk: '+searchKeywords);
			if(searchKeywords!=null || is_array(searchKeywords)){
				var indexNode=0;
				
				
									
				while(searchKeywords.length>0){
					
					
					
					var node = searchKeywords.shift();
					
					var idCondMulti = 'cond' + new Date().getTime();
					//console.log("idCondMulti "+idCondMulti);
					if( !(node['value'] === undefined) && node['value'] != '' && idCondMulti!="undefined"){	
						
						if ( !(node['logicalOperator'] === undefined) ){
							var divOr = $("<div>");
							divOr.attr("class","search_main_relation_" + node['logicalOperator']);
							var id =idCondMulti;
			  				divOr.attr("id",id);
							var imgRel = $("<img>");
							
							imgRel.attr('src', 'fileadmin/templates/images/relation_' + node['logicalOperator'] + '.gif');
							imgRel.attr('title', '');
							imgRel.attr('alt', '');
														
							imgRel.attr('onclick', 'this.src="fileadmin/templates/images/relation_" + this.getAttribute("rel") + ".gif"; this.setAttribute("class","search_main_relation_" + this.rel);if( this.getAttribute("rel") =="or"){this.setAttribute("rel", "and");}else{this.setAttribute("rel", "or");}');
							
							imgRel.attr('ref', id);
							if(node['logicalOperator'] == 'or'){
								imgRel.attr('rel', 'and');
							}else{
								imgRel.attr('rel', 'or');
							}
							divOr.append(imgRel);
							relDiv.append(divOr);
						
						
						}
						//console.log("bazinga");
						var divTab = $("<div>");
						divTab.attr("class","search_main_tag");
		  				
		  				var id = "tag" + new Date().getTime();
		  				divTab.attr("id",id);
					
						var pTag = $("<p>");
						//console.log('node: '+node['value']);
		  				pTag.html(node['value']);
						
						//var divClear = document.createElement("span");
						//divClear.setAttribute("class","clear");
						
						var imgTag = $("<img>");
						imgTag.attr('class', 'deleteTag');
						imgTag.attr('src', 'fileadmin/templates/images/delete.gif');
						imgTag.attr('title', 'löschen');
						imgTag.attr('alt', 'löschen');
						imgTag.attr('ref', id);
						imgTag.attr('relCond', idCondMulti);
						
						//console.log(tagsDiv);
						divTab.append(imgTag);
						divTab.append(pTag);
						//console.log(divTab);
						//divTab.appendChild(divClear);
						tagsDiv.append(divTab);
						indexNode++;
						txTag.val('');
						
						
					}	
				}
				
				//deleteNodeRel("' + id  + '", "' + idCondMulti + '");$("' + id + '").destroy();
				
			}
			
			//console.log(tagsDiv);
			//console.log(relDiv);
			var tagsCount = $('div.search_main_tag').length;
			var logicalCount = $('#search_main_relation div').length;
	
	//console.log(tagsCount+"//"+logicalCount);				
	if( (logicalCount) < (tagsCount-1) ){
				 var divOr = $("<div>");
				 
				divOr.attr("class","search_main_relation_and");		
				divOr.attr("id",idCondMulti);
  				
				var imgRel = $("<img>");
				imgRel.attr('class', 'changeRel');
				imgRel.attr('src', 'fileadmin/templates/images/relation_and.gif');
				imgRel.attr('title', '');
				imgRel.attr('alt', '');										
				imgRel.attr('ref', id);
				imgRel.attr('rel', 'or');

					divOr.append(imgRel);
					relDiv.append(divOr);
						
				
			}

					
		}
	}
	if(i==0)
	{
		// Initialization for the click events on the tags 
		tagClickEvents();
	}
	i++;
	});
}
function tagClickEvents(){
	$jq(function($) {
		$('.changeRel').live('click', function() {
    		//console.log($(this).attr("rel"));
    		$(this).attr("src","fileadmin/templates/images/relation_" + $(this).attr("rel") + ".gif");
	   		$(this).attr("class","search_main_relation_" + $(this).attr("rel") + ' changeRel');
	   		if($(this).attr("rel") == "or"){
	   			$(this).attr("rel", "and");
	   		}else{
	   			$(this).attr("rel", "or");
	   		}  
	   		return false;
    	});
    	$('.deleteTag').live('click', function() {
			$('#'+$(this).attr('relCond')).remove();
			$('#'+$(this).attr('ref')).remove();
			return false;
    	});
	});
}

function onSubmit(event){
    //onAddTag(event);
	var tagsDiv = null;
	tagsDiv = $('search_main_tags');
	
	var relDiv = null;
	relDiv = $('search_main_relation');
	var bufferKeywords = ''; 
	if( (tagsDiv!=null && relDiv!=null)){
		tagsArray = tagsDiv.getChildren('div');
		relArray = relDiv.getChildren('div');
		if(tagsArray.length == 0){
			$('search_main_form').setAttribute('onsubmit', 'return false');
		}
		//console.log(tagsArray.length);
		while(tagsArray.length>0){
			var relNode = null; 
			relNode = relArray.pop();
			var tagNode = tagsArray.pop();
			var p = tagNode.getFirst('p');
			
			if(p.innerHTML!=""){
				//console.log("pinner "+p.innerHTML);
				bufferKeywords = bufferKeywords + p.innerHTML;
			}
			//console.log("bufferkeys "+bufferKeywords);
			//console.log("relNode "+relNode);
			if(relNode!=null){
				var imgCon = relNode.getFirst('img');		
				if(imgCon.getAttribute('rel') == 'or'){
					bufferKeywords = bufferKeywords + '+';
				}else if(imgCon.getAttribute('rel') == 'and'){
					bufferKeywords = bufferKeywords + '|';
				}
			}
		}
		$('search_main_temp').value = bufferKeywords;
		//console.log("bufferkeys "+bufferKeywords);
		$('search_main_form').setAttribute('onsubmit', '');
		$('search_main_form').submit();
		return true;
	}
	return false;
}

function miniParser(string){
	var Nodes = new Array();
	string = string.replace(/((?:^|\s)(oder)(?=\s|$))|((?:^|\s)(or)(?=\s|$))/gi, "|")
	string = string.replace(/((?:^|\s)(und)(?=\s|$))|((?:^|\s)(and)(?=\s|$))/gi, "+")
	
	var index=0;
	var buffer = '';
	while(string.length>0){
		var lastChar = string.charAt(string.length-1);
		if(lastChar == '|'){
			var tempNode = new Array();
			tempNode ['value'] = trim(buffer);
			tempNode ['logicalOperator'] = 'or';
			buffer = '';
			Nodes[index] = tempNode;
			index++;
		}else if( lastChar == '+' ){
			tempNode = new Array();
			tempNode ['value'] =  trim(buffer);
			tempNode ['logicalOperator'] = 'and';
			buffer = '';
			Nodes[index] = tempNode;
			index++;
		}else{
			buffer =  lastChar  +  buffer;
		}
		if(string.length == 1){
			tempNode = new Array();
			tempNode ['value'] = buffer;
			Nodes[index] = tempNode;
		}
		string = string.substr(0,string.length-1);	
	}
	//console.log("nodes "+Nodes);
	return Nodes;
}


// Deprecated via jQuery
/*function trim (value) {

return value.replace (/^\s+/, '').replace (/\s+$/, '');
}*/



function filterClick(){

if($('filterStatus').value=='active'){
	$('filterStatus').value='inactive';
}else{
	$('filterStatus').value='active';
}

}

function removeGalleryNav(){
	var galleryItems = jQuery('#container_slider li').size();
	
	if(galleryItems <= 5){
		jQuery('#slider_prev, #slider_next').remove();
	}	
}
// Integrates facebook and twitter share button after document.ready();
function initializeSocialMedia(){
	var fbContainer = jQuery('div.likes');
	var twContainer = jQuery('div.tweets');
	
	var fbUrl = jQuery('div.likes span.hide').html();
	var twUrl = jQuery('div.tweets span.hide').html();
	
	fbContainer.html('<iframe src="http://www.facebook.com/plugins/like.php?href=' + fbUrl + '&amp;layout=button_count&amp;show_faces=true&amp;width=106&amp;action=recommend&amp;colorscheme=light&amp;height=22" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:106px; height:22px;" allowTransparency="true"></iframe>');
	twContainer.html('<a href="http://twitter.com/share" class="twitter-share-button" data-url="' + twUrl + '" data-count="horizontal" data-lang="de">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>');
}


JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

function flapBoxes(){
	// Contains status off elements
	
	jQuery(".inactive").next('.widget-content').each(function(){
		jQuery(this).css({"display":"none"});
	});
	
	jQuery(".widget-toggle").click(function(){
		if(jQuery(this).parent().next(".widget-content").attr("id")=="search_main_filter_options"){
			if(jQuery(this).closest('.active').length > 0){	
				jQuery(this).closest('.active').removeClass("active").addClass("inactive");
				generateStatus();
				jQuery('#search_main_filter_options div').fadeOut('fast', function(){
					jQuery('#search_main_filter_options').slideUp();
				});
			}else{
				jQuery(this).closest('.inactive').removeClass("inactive").addClass("active");
				jQuery('#search_main_filter_options div').css({'display':'none'});
				generateStatus();
				jQuery('#search_main_filter_options').css({'height':'220px'});
				jQuery('#search_main_filter_options').slideDown('medium', function(){
					jQuery('#search_main_filter_options div').fadeIn();
				});
				
			}
			return false;
		}
		if(jQuery(this).parent().next(".widget-content").length > 0){
			if(jQuery(this).closest('.active').length > 0){
				jQuery(this).closest('.active').removeClass("active").addClass("inactive");
			}else{
				jQuery(this).closest('.inactive').removeClass("inactive").addClass("active");
			}
			jQuery(this).parent().next(".widget-content").slideToggle("medium", function(){
				generateStatus();
			});
		}
		if(jQuery(this).next(".widget-content").length > 0){
			if(jQuery(this).closest('.active').length > 0){
				jQuery(this).next(".widget-content").slideToggle("medium", function(){
					jQuery(this).closest('.active').removeClass("active").addClass("inactive");
					generateStatus();
				});
			}else{
				jQuery(this).closest('.inactive').removeClass("inactive").addClass("active");
				jQuery(this).next(".widget-content").slideToggle("medium",function(){
					generateStatus();
				});
			}
		}
	});
	jQuery('.rgaccord1-nest .rgaccord1-content').each(function(){
		jQuery(this).wrap('<div class="inactive" style="clear:both;" />');
	});
	jQuery(".rgaccord1-toggle").click(function(){
		console.log(jQuery(this).next('div.inactive').children());
		if(jQuery(this).next('div.inactive').children().length > 0){
			console.log(jQuery(this).next('div.inactive').children().height());
			jQuery(this).next('div.inactive').children().slideToggle("slow");
		}
		return false;
	});
}

function generateStatus(){
	var status = {};
	jQuery(".widget").each(function(){
		if(jQuery(this).attr("id")){

			var id = jQuery(this).attr("id").toString();
			if(jQuery(this).find(".active").length > 0){
				if(jQuery(this).attr("id")=="search_main_filter"){
					jQuery('#filterStatus').val("active");
				}
				status[id] = jQuery(this).find(".active").attr("class");
			}
			if(jQuery(this).find(".inactive").length > 0){
				if(jQuery(this).attr("id")=="search_main_filter"){
					jQuery('#filterStatus').val("inactive");
				}
				status[id] = jQuery(this).find(".inactive").attr("class");
			}
			//console.log(JSON.stringify(status));
		}
	});	
	var statusString = JSON.stringify(status);
	$jq.cookie('status', statusString, {expires:365, path: '/'});
}

function checkBoxStatus(){
	jQuery('#search_main_filter_options').css({'height':'220px'});
	if($jq.cookie("status")){
		
		var boxStatus = jQuery.parseJSON($jq.cookie("status"));
		$jq.each(boxStatus, function(index, value){
			if(value == "inactive"){
				var display = "none";
				var status = "inactive";
			}else{
				var display = "block";
				var status = "active";
			}
			if(index == "search_main_filter"){
				jQuery('#filterStatus').attr({'value':status});
			}
			if(jQuery('#'+index).find(".active").length > 0){
				jQuery('#'+index).find(".active").attr("class", value);
				jQuery('#'+index).find(".widget-content").css({'display':display});
				if(index == "search_main_filter"){
					jQuery('#search_main_filter_options div').css({'display':display});
				}
			}
			if(jQuery('#'+index).find(".inactive").length > 0){
				jQuery('#'+index).find(".inactive").attr("class", value);
				jQuery('#'+index).find(".widget-content").css({'display':display});
				if(index == "search_main_filter"){
					jQuery('#search_main_filter_options div').css({'display':display});
				}
			}
		}) 		
	}
} 




