(function($){

// PAGE SCROLL

	$.localScroll( {
		offset: -75,
		duration: 400
	});		

// FIXEDMENU
  
	var msie6 = $.browser == 'msie' && $.browser.version < 7;
	  
	  if (!msie6) {
		var top = $('#mainmenu').offset().top - parseFloat($('#mainmenu').css('margin-top').replace(/auto/, 0));
		$(window).scroll(function (event) {
		  var y = $(this).scrollTop();
		  if (y >= top) {
			$('#mainmenu, #intro').addClass('fixed');
		  } else {
			$('#mainmenu, #intro').removeClass('fixed');
		  }
		});
	  }  

// NAVI HIGHLIGHT

    var $sections = $('#verkkokaupat, #internetsivut, #referenssit, #yhteystiedot, #end'); 
	var $navs = $('#mainmenu ul li');
	
	var topsArray = $sections.map(function() {
	    return $(this).position().top - 300;
	}).get();

	var len = topsArray.length; 
	var currentIndex = 0;
	
	var getCurrent = function( top ) {
	    for( var i = 0; i < len; i++ ) {
	        if( top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1] ) {
	            return i;
	        }
	    }
	};
	
	$(window).scroll(function(e) {
	    var scrollTop = $(this).scrollTop();
	    var checkIndex = getCurrent( scrollTop );
	    if( checkIndex !== currentIndex ) {
	        currentIndex = checkIndex;
	        $navs.eq( currentIndex ).addClass("selected").siblings(".selected").removeClass("selected");
	    }
	});

// CONTACT FORM
	$("#contactform").validate({
			submitHandler: function(form) {
				$.post('index.php', $("#contactform").serialize(), function(data) {
				$('#contact_form').html("<p>&nbsp;</p><div id='success'><h3>Kiitos yhteydenotostasi!</h3><p>Vastaan viestiisi mahdollisimman pian.</p></div>")
				.append()
				.hide()
				.fadeIn(500, function() {
				      $('#contact_form');
				    });
				});
			},
			messages: {
			name: "Kirjoita nimesi &uarr;",
			email: "Kirjoita toimiva sähköpostiosoite &uarr;",
			message: "Kirjoita viestisi &uarr;"
			}
	});

// TABBED CONTENT

	var TabbedContent = {
		init: function() {	
			$(".tab_item").click(function() {
			
				var background = $(this).parent().find(".moving_bg");
				
				$(background).stop().animate({
					left: $(this).position()['left']
				}, {
					duration: 300
				});
				
				TabbedContent.slideContent($(this));
				
			});
		},
		
		slideContent: function(obj) {
			
			var margin = $(obj).parent().parent().find(".slide_content").width();
			margin = margin * ($(obj).prevAll().size() - 1);
			margin = margin * -1;
			
			$(obj).parent().parent().find(".tabslider").stop().animate({
				marginLeft: margin + "px"
			}, {
				duration: 300
			});
		}
	}

	TabbedContent.init();

// EXTERNAL LINKS

	jQuery("a[href^='http:']").not("[href*='emerca.net']").attr('target','_blank'); 
	

})(this.jQuery);


