jQuery.noConflict();

jQuery(document).ready(function(){
	// activates the lightbox page, if you are using a dark color scheme use another theme parameter
	my_lightbox("a[rel^='prettyPhoto'], a[rel^='lightbox']",true);
	k_smoothscroll();
	
	// cufon font replacement
	//font_improvement('h1, #featured:not(.curtain, .accordion, .newsslider) .sliderheading');
	
	// news slider
	jQuery('.newsslider').kriesi_news_slider({
			slides: '.featured',				// wich element inside the container should serve as slide
			animationSpeed: 900,				// animation duration in milliseconds
			autorotation: true,					// autorotation true or false?
			autorotationSpeed:5					// duration between autorotation switch in Seconds
	});

	jQuery('.item_data').equalHeights();

	jQuery('.ajax_form').kriesi_ajax_form();	// activates contact form
	jQuery('input:text').kriesi_empty_input();	// comment form improvement
	
	var selectImg = '#main';
	if (jQuery.browser.msie) selectImg = '.portfolio_item, .image_border'
	jQuery(selectImg).kriesi_image_preloader({delay:200});	// activates preloader for non-slideshow images

	jQuery(window).scroll(function(){
		if(jQuery(window).scrollTop() > 1000){
			jQuery('#back_to_top').stop().animate({'opacity': 1});
		}else{
			jQuery('#back_to_top').stop().animate({'opacity': 0});
		}
	});

});

jQuery(document).load(function(){
	k_menu(); // controls the dropdown menu
});

function font_improvement($selectors){
	jQuery($selectors).each(function()
	{
		$size = parseInt(jQuery(this).css('fontSize'));	
		jQuery(this).css('fontSize', $size * 1.4)
	});

	Cufon.replace($selectors,{ fontFamily: 'geosans' });
}



// -------------------------------------------------------------------------------------------
// input field improvements
// -------------------------------------------------------------------------------------------

(function($)
{
	$.fn.kriesi_empty_input = function(options) 
	{
		return this.each(function()
		{
			var currentField = $(this);
			currentField.methods = 
			{
				startingValue:  currentField.val(),
				
				resetValue: function()
				{	
					var currentValue = currentField.val();
					if(currentField.methods.startingValue == currentValue) currentField.val('');
				},
				
				restoreValue: function()
				{	
					var currentValue = currentField.val();
					if(currentValue == '') currentField.val(currentField.methods.startingValue);
				}
			};
			
			currentField.bind('focus',currentField.methods.resetValue);
			currentField.bind('blur',currentField.methods.restoreValue);
		});
	}
})(jQuery);	


	
// -------------------------------------------------------------------------------------------
// The Image preloader
// -------------------------------------------------------------------------------------------


(function($)
{
	$.fn.kriesi_image_preloader = function(options) 
	{
		var defaults = 
		{
			repeatedCheck: 500,
			fadeInSpeed: 1000,
			delay:600,
			callback: ''
		};
		
		var options = $.extend(defaults, options);
		
		return this.each(function()
		{
			var imageContainer = jQuery(this),
				images = imageContainer.find('img').css({opacity:0, visibility:'hidden'}),
				imagesToLoad = images.length;				
				
				imageContainer.operations =
				{	
					preload: function()
					{	
						var stopPreloading = true;
						
						images.each(function(i, event)
						{	
							var image = $(this);
							
							
							if(event.complete == true)
							{	
								imageContainer.operations.showImage(image);
							}
							else
							{
								image.bind('error load',{currentImage: image}, imageContainer.operations.showImage);
							}
							
						});
						
						return this;
					},
					
					showImage: function(image)
					{	
						imagesToLoad --;
						if(image.data.currentImage != undefined) { image = image.data.currentImage;}
												
						if (options.delay <= 0) image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
												 
						if(imagesToLoad == 0)
						{
							if(options.delay > 0)
							{
								images.each(function(i, event)
								{	
									var image = $(this);
									setTimeout(function()
									{	
										image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
									},
									options.delay*(i+1));
								});
								
								if(options.callback != '')
								{
									setTimeout(options.callback, options.delay*images.length);
								}
							}
							else if(options.callback != '')
							{
								(options.callback)();
							}
							
						}
						
					}

				};
				
				imageContainer.operations.preload();
		});
		
	}
})(jQuery);


// -------------------------------------------------------------------------------------------
// The News Slider
// -------------------------------------------------------------------------------------------

(function($)
{
	$.fn.kriesi_news_slider= function(options) 
	{
		var defaults = 
		{
			slides: '>div',				// wich element inside the container should serve as slide
			animationSpeed: 900,		// animation duration
			autorotation: true,			// autorotation true or false?
			autorotationSpeed:3,		// duration between autorotation switch in Seconds
			easing: 'easeOutQuint'
		};
		
		var options = $.extend(defaults, options);
		
		return this.each(function()
		{
			var slideWrapper 	= $(this),								
				slides			= slideWrapper.find(options.slides).css({display:'none',zIndex:0}),
				slideCount 	= slides.length,
				accelerator = 0,				// accelerator of scrolling speed
				scrollInterval = '',			// var that stores the setInterval id
				mousePos = '',					// current mouse position
				moving = false,					// scrollbar currently moving or not?
				controllWindowHeight = 0,		// height of the wrapping element that hides overflow
				controllWindowPart = 0,			// mouseoverpart of the wrapping element that hides overflow
				itemWindowHeight = 0,			// height of element to move
				current_class = 'active_item',
				skipSwitch = true,
				currentSlideNumber = 0,
				newsSelect ='',
				newsItems = '';				
				
				slideWrapper.methods = {
				
					init: function()
					{
						newsSelect = $('<div></div>').addClass('newsselect').appendTo(slideWrapper);
						newsItems = $('<div></div>').addClass('newsItems').appendTo(newsSelect);
						fadeout = $('<div></div>').addClass('fadeout').addClass('').appendTo(slideWrapper);
						
						slides.filter(':eq(0)').css({zIndex:2, display:'block'});
						
						slides.each(function(i)
						{	
							var slide = $(this),
								url = slide.find('a').attr('href'),
								controll = $('<a class="single_item '+current_class+'"></a>').appendTo(newsItems).attr('href',url);
								current_class ='';
								
							slide.find('.feature_excerpt .sliderheading, .feature_excerpt .sliderdate').clone().appendTo(controll);
							controll.bind('click', {currentSlideNumber: i}, slideWrapper.methods.switchSlide);
						});
						
						controllWindowHeight = newsSelect.height();
						controllWindowPart = controllWindowHeight/3;
						itemWindowHeight = newsItems.height();
						
						if(slideCount > 1)
						{
							slideWrapper.kriesi_image_preloader({delay:200});
							slideWrapper.methods.preloadingDone();
						}
					},
					
					preloadingDone: function()
					{	
						skipSwitch = false;
						var offset = newsSelect.offset();
						
						newsSelect.mousemove(function(e)
						{
							mousePos = e.pageY - offset.top;
							
							if(!moving)
							{
								scrollInterval = setInterval(function() { slideWrapper.methods.scrollItem(mousePos); }, 25);
								moving = true;
							}
						}); 
										
						newsSelect.bind('mouseleave', function()
						{ 
							clearInterval(scrollInterval); 
							moving = false;
							accelerator = 0;
						});
						
					},
					
					scrollItem: function()
					{	
						var movement = 0,
							percent = controllWindowPart / 100,
							modifier = 10,
							currentTop = parseInt(newsItems.css('top'));
							
						accelerator = accelerator <= 2 ? accelerator + 0.5 : accelerator; 
						
						if(mousePos < controllWindowPart)
						{	
							movement = ((controllWindowPart - mousePos) / percent) * accelerator;
							newPos = currentTop + (movement/modifier);
							
							if(currentTop < 0)
							{	
								if (newPos > 0) newPos = 0;
								newsItems.css({top:newPos + "px"});
							}
						}
						else if(mousePos > controllWindowPart * 2)
						{	
							movement = ((mousePos - controllWindowPart * 2) / percent) * accelerator;
							newPos = currentTop + (movement/modifier * -1);
							
							if((currentTop * -1) < itemWindowHeight - controllWindowHeight)
							{
								if (newPos * -1 > itemWindowHeight - controllWindowHeight) newPos = controllWindowHeight - itemWindowHeight;
								
								newsItems.css({top:newPos + "px"});
							}
						}
						else
						{
							accelerator = 0;
						}
					},
					
					switchSlide: function(passed)
					{	
						
						var noAction = false;
						
						if(passed != undefined && !skipSwitch)
						{
							if(currentSlideNumber != passed.data.currentSlideNumber)
							{	
								currentSlideNumber = passed.data.currentSlideNumber;
							}
							else
							{
								noAction = true;
							}
						}
						
						if(passed != undefined)
						{	
							// clearInterval(interval);
						}
						
						
						if(!skipSwitch && noAction == false)
						{	
							skipSwitch = true;
							var currentSlide = slides.filter(':visible'),
								nextSlide = slides.filter(':eq('+currentSlideNumber+')');
																
							newsSelect.find('.active_item').removeClass('active_item');
							newsSelect.find('a:eq('+currentSlideNumber+')').addClass('active_item');	
																
							currentSlide.css({zIndex:4});
							nextSlide.css({zIndex:2, display:'block'});
							
							currentSlide.fadeOut(options.animationSpeed, function()
							{
								currentSlide.css({zIndex:0, display:"none"});
								skipSwitch = false;
							});
						}
						return false;
					},
					
					autorotate: function()
					{	
						//autorotation not yet supportet
					}
				
				};
				
				slideWrapper.methods.init();
		});
		
	}
})(jQuery);


function k_menu()
{
	// k_menu controlls the dropdown menus and improves them with javascript
	
	jQuery("#nav a").removeAttr('title');
	jQuery(" #nav ul").css({display: "none"});
	
	//smooth drop downs
	jQuery("#nav li").each(function()
	{	
		var $sublist = jQuery(this).find('ul:first');
		
		$sublist.find('>li:first').css('marginTop','5px');
		$sublist.find('>li:last').css('marginBottom','5px');
		
		jQuery(this).hover(function()
		{	
			$sublist.stop().css({overflow:"hidden", height:"auto", display:"none",'paddingTop':'0px','paddingBottom':'0px'}).slideDown(400, function()
			{
				jQuery(this).css({overflow:"visible", height:"auto"});
			});
		},
		function()
		{	
			$sublist.stop().slideUp(400, function()
			{	
				jQuery(this).css({overflow:"hidden", display:"none"});
			});
		});	
	});
}


//equalHeights by james padolsey
jQuery.fn.equalHeights = function() {
    return this.height(Math.max.apply(null,
        this.map(function() {
           return jQuery(this).height()
        }).get()
    ));
};


function my_lightbox($elements, autolink)
{	
	var theme_selected = 'light_rounded';
	
	if(autolink)
	{
		jQuery('a[href$=jpg], a[href$=png], a[href$=gif], a[href$=jpeg], a[href$=.mov] , a[href$=.swf] , a[href*=vimeo.com] , a[href*=youtube.com]').contents("img").parent().each(function()
		{
			if(!jQuery(this).attr('rel') != undefined && !jQuery(this).attr('rel') != '' && !jQuery(this).hasClass('noLightbox'))
			{
				jQuery(this).attr('rel','lightbox[auto_group]')
			}
		});
	}
	
	jQuery($elements).prettyPhoto({
			"theme": theme_selected /* light_rounded / dark_rounded / light_square / dark_square */																	});
	
	jQuery($elements).each(function()
	{	
		var $image = jQuery(this).contents("img");
		$newclass = 'lightbox_video';
		
		if(jQuery(this).attr('href').match(/(jpg|gif|jpeg|png|tif)/)) $newclass = 'lightbox_image';
			
		if ($image.length > 0)
		{	
			if(jQuery.browser.msie &&  jQuery.browser.version < 7) jQuery(this).addClass('ie6_lightbox');
			
			var $bg = jQuery("<span class='"+$newclass+" '></span>").appendTo(jQuery(this));
			
			jQuery(this).bind('mouseenter', function()
			{
				$height = $image.height();
				$width = $image.width();
				$pos =  $image.position();		
				$bg.css({height:$height, width:$width, top:$pos.top, left:$pos.left});
			});
		}
	});	
	
	jQuery($elements).contents("img").hover(function()
	{
		jQuery(this).stop().animate({opacity:0.5},400);
	},
	function()
	{
		jQuery(this).stop().animate({opacity:1},400);
	});
}


(function($)
{
	$.fn.kriesi_ajax_form = function(options) 
	{
		var defaults = 
		{
			sendPath: 'send.php',
			responseContainer: '.ajaxresponse'
		};
		
		var options = $.extend(defaults, options);
		
		return this.each(function()
		{
			var form = $(this),
				send = 
				{
					formElements: form.find('textarea, select, input:text, input[type=hidden]'),
					validationError:false,
					button : form.find('input:submit'),
					datastring : ''
				};
			
			send.button.bind('click', checkElements);
			
			function send_ajax_form()
			{
				send.button.fadeOut(300);	
									
				$.ajax({
					type: "POST",
					url: options.sendPath,
					data:send.datastring,
					success: function(response)
					{	
						
						var message =  $("<div'></div>").addClass(options.responseContainer)
														.css('display','none')
														.insertBefore(form)
														.html(response); 
														
						form.slideUp(400, function(){message.slideDown(400), send.formElements.val('');});
						
					}
				});
				
			}
			
			function checkElements()
			{	
				// reset validation var and send data
				send.validationError = false;
				send.datastring = 'ajax=true';
				
				send.formElements.each(function(i)
				{
					var currentElement = $(this),
						surroundingElement = currentElement.parent(),
						value = currentElement.val(),
						name = currentElement.attr('name'),
					 	classes = currentElement.attr('class'),
					 	nomatch = true;
					 	
					 	send.datastring  += "&" + name + "=" + value;
					 	
					 	if(classes.match(/is_empty/))
						{
							if(value == '')
							{
								surroundingElement.attr("class","").addClass("error");
								send.validationError = true;
							}
							else
							{
								surroundingElement.attr("class","").addClass("valid");
							}
							nomatch = false;
						}
						
						if(classes.match(/is_email/))
						{
							if(!value.match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/))
							{
								surroundingElement.attr("class","").addClass("error");
								send.validationError = true;
							}
							else
							{
								surroundingElement.attr("class","").addClass("valid");
							}	
							nomatch = false;
						}
						
						if(nomatch && value != '')
						{
							surroundingElement.attr("class","").addClass("valid");
						}
				});
				
				if(send.validationError == false)
				{
					send_ajax_form();
				}
				return false;
			}
		});
	}
})(jQuery);



function k_smoothscroll()
{
	jQuery('a[href*=#]').click(function() {
		
	   // duration in ms
	
	   var newHash=this.hash,
		   target=jQuery(this.hash).offset().top,
		   oldLocation=window.location.href.replace(window.location.hash, ''),
		   newLocation=this,
		   duration=800,
		   easing='easeOutQuint';
		
		
	   // make sure it's the same location      
	   if(oldLocation+newHash==newLocation)
	   {
	      // animate to target and set the hash to the window.location after the animation
	      jQuery('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing, function() {
	
	         // add new hash to the browser location
	         window.location.href=newLocation;
	      });
	
	      // cancel default click action
	      return false;
	   }
	
	});
}

