jQuery(function($){
	// Link every post image to the post
	function linkPostImages(){
		$('.teaser-post').each(function() {
			$('img', this).css('cursor', 'pointer');

			var link = $('a', this).attr('href');
			$('img', this).click(function() {

				if($(this).hasClass('autoplay')) {
					$(this).before('<form method=\'post\' action=\'' + link + '\' id=\'post-autoplay\'><input type=\'hidden\' name=\'autoplay\' /></form>');
					$('#post-autoplay').submit();
				} else {
					window.location.href = link;
				}
			});
		});
	}
	


	// Make the search field animated
	function animateSearchField() {
		$('div.search input[type="text"]')
		.css("width", 161)
		.addClass("idleField")
		.focus(function() {
			$(this).removeClass("idleField").addClass("focusField");
			$(this).stop().animate({width: 238}, 500);
		})
		.blur(function() {
			$(this).removeClass("focusField").addClass("idleField");
			$(this).stop().animate({width: 161}, 500);

			if ($.trim(this.value == '')){
				this.value = (this.defaultValue ? this.defaultValue : '');
			}
		});
	}

	function tellFriend() {
		tipsaOpen = false;
		$("#tipsa-box").hide();
		$("#tipsa p:first").css({"cursor": "pointer", "text-decoration": "underline"});

		$("#tipsa").hover(function () {
			if(tipsaOpen) {
				clearTimeout(tellTimer);
			} else {
				$("#tipsa-box").show();
				tipsaOpen = true;
			}
		}, function() {
			tellTimer = setTimeout(function() {
				$("#tipsa-box").fadeOut(700);			
				tipsaOpen = false;
			}, 1000);
		});

		function fbs_click() {
		    u = location.href;t=document.title;window.open("http://www.facebook.com/sharer.php?u=" + encodeURIComponent(u) + "&t=" + encodeURIComponent(t), "sharer","toolbar=0,status=0,width=626,height=436");
		    return false;
		}
	}
	

	function billboard(obj, autoSwitch, autoSwitchTime, clickAction) {
		var totalSlides = $('.slide', obj).length;
		var currentSlide = 1;
		var preventSwitch = false;
		var cursorIsOver = false;
		var timer;
		
		$(obj).css('cursor', 'pointer');
		$(obj).addClass('slideshow');
		setSlideshowSize();

		$('.slide', obj).click(function() {
			stopAutoSwitch();

    		if($('a:first', this).attr('href') == "http://www.preview11.se/blogg/forhandsboka-preview-11/") {
				if (($('.order').css("height") == '0px')) {
					$('.order').stop().animate({'height':'560px'},400);
					$('.order').addClass("active");
				} else {
					$('.order').stop().animate({'height':'0px'},300);
					$('.order').removeClass("active");
				}

				return false;
    		} else if(clickAction == 'link')
    			window.location.href = $('a:first', this).attr('href');
    		else
    			if(showSlideshow())
    				switchSlide(getNextSlide());
		});
		
		if(showSlideshow()) {
			launchSlideshow();
		}
		
		function showSlideshow() {
			return (totalSlides <= 1 ? false : true);
		}
		
		function launchSlideshow() {			
			addSlideNumbers();
			createNavigation();
			
			$(obj).hover(function() {
				cursorIsOver = true;
				$('.navigation', obj).stop().animate({opacity:1}, 400);
				
			}, function() {
				cursorIsOver = false;
				$('.navigation', obj).stop().animate({opacity:0}, 400);
			});

			if(autoSwitch)
				timer = setInterval(function() { autoSwitchSlide(); }, autoSwitchTime);
				
			controllerTimer = setTimeout(function() {
				if(!cursorIsOver) {
					$('.navigation', obj).animate({opacity:0}, 400);
					clearTimeout(controllerTimer);
				}
			}, 3000);

			$('.slide', obj).css('cursor', 'pointer');
			$('.slide_' + currentSlide).addClass('active');
		}
		
		function autoSwitchSlide() {
			if(autoSwitch && !cursorIsOver)
				switchSlide(getNextSlide());
		}
		
		function switchSlide(targetSlide) {
			targetSlide = parseInt(targetSlide);
			if(!preventSwitch) {
				preventSwitch = true;

				$('.slide.last-active', obj).removeClass('last-active');
				$('.slide.active', obj).removeClass('active').addClass('last-active').fadeOut();
				$('.slide_' + targetSlide, obj).addClass('active').fadeIn();
				switchNavigationHighlight(targetSlide);
				
				setTimeout(function() { preventSwitch = false; }, 300);
				
				currentSlide = targetSlide;

				return true;
			}

			return false;
		}
		
		function getNextSlide() {
			return (currentSlide != totalSlides) ? currentSlide + 1 : 1;
		}
		
		function addSlideNumbers() {
			$('.slide', obj).each(function(index) {
				$(this).addClass('slide_' + (index+1))
			});
			
			return true;
		}
		
		function createNavigation() {
			$('.slide:last', obj).after('<ul class="navigation"></ul>');
			$('.slide', obj).each(function(index) {
				$('.navigation', obj).prepend('<li class="nav_' + (index+1) + '">' + (index+1) + '</li>');
			});

			$('.navigation li', obj).css("cursor", "pointer");
			
			$('.navigation li.nav_' + currentSlide, obj).addClass('active');
			
			$('.navigation li', obj).click(function() {
				stopAutoSwitch();

				if(!$(this).hasClass('active') && !preventSwitch) {
					switchSlide($(this).html());
				}
			});
			
			return true;
		}
		
		function switchNavigationHighlight(target) {
			$('.navigation li.active', obj).removeClass('active');
			$('.navigation li.nav_' + target).addClass('active');
			
			return true;
		}
		
		function setSlideshowSize() {
			slideshowHeight = $('img:first', obj).attr('height');
			if(slideshowHeight > 0)
				$(obj).css('height', slideshowHeight);
				
			slideshowWidth = $('img:first', obj).attr('width');
			if(slideshowWidth > 0)
				$(obj).css('width', slideshowWidth);
		}

		function stopAutoSwitch() {
			clearInterval(timer);
			autoSwitch = false;
		}
	}
	


	$('#tavling li').each(function(index) {
		$(this).css('opacity', (1 - (index*0.1)) );
	});

	
	function randomHighlight() {
		var entryAmount = $('#tavling .entry').length;
		var randomNumber = 0;
		var restartAutomaticTimer; // countdown to start the automatic switching again
		var entryInfoTimer; // countdown to show entry information on hover
		
		$('#tavling .entry.entered').css('cursor', 'pointer');
		$('#tavling .entry.empty img.color').css('opacity', 0);

		$('#tavling .entry.entered').click(function() {
   			window.location.href = $('a:first', this).attr('href');
		});

		// if javascript is on, set it to active
		$('#tavling').removeClass('inactive');

		// abort script if there are no entries
		if($('#tavling .entry').length == 0)
			return false;

		// start automatic highlighting
		activateAutomaticHighlight();

		$('#tavling .entry').hover(function () {
			
			currentEntry = this;
			clearInterval(highlightInterval);
			$('img.color', currentEntry).stop().animate({opacity:1}, 200);

			// if active, instantly abort the automatic switch
 			if(randomNumber != 0) {
	 			$('#tavling .entry.entered:nth-child(' + randomNumber + ') img.color').clearQueue().animate({opacity:0}, 200);
	 			randomNumber = 0;
			}

			entryInfoTimer = setTimeout( function() {
				$('.likes', currentEntry).stop().animate({'bottom':'0px'}, 200);
				$('.name', currentEntry).stop().animate({'top':'0px'}, 200);
			}, 500);

		}, function () {

			$('img.color', currentEntry).stop().animate({opacity:0}, 200);
			$('.likes', currentEntry).stop().animate({'bottom':'-31px'}, 200);
			$('.name', currentEntry).stop().animate({'top':'-34px'}, 200);
			
			activateAutomaticHighlight();
			clearTimeout(entryInfoTimer);

		});

		function activateAutomaticHighlight() {
			highlightInterval = setInterval(function() {
				randomNumber = getRandomNumber();
				$('#tavling .entry:nth-child(' + randomNumber + ') img.color').stop().animate({opacity:.8},1000).delay(2000).animate({opacity:0},1000);
			}, 4000);
		}

		function getRandomNumber() {
			done = false;

			while(!done) {
				newRandomNumber = Math.floor(Math.random() * entryAmount) + 1;

				if(newRandomNumber != randomNumber || entryAmount <= 1)
					done = true;
			}

			return newRandomNumber;
		}
	}

	
	$('#javascript').val('1')
	
	preorderSending = false;
	var btnText = $('.order #button').text();
	$('.order #button').css('cursor', 'pointer');
	$('.order #button').click(function() {

		if(!preorderSending) {

			$('.order #button').html('<img src="http://www.preview11.se/wp-content/themes/p11_experiment/js/ajax-loader.gif" alt=""/>');
			
			preorderSending = true;
			
			$.post('http://www.preview11.se/experiment/preorder', $('.order form').serialize() + '&preorderSubmit=1',
			function(data){
				if(data == '1') {
					showSuccessMessage();
					$('.order #button').text(btnText);
				} else if (data == '2') {

					$('.order #button').text(btnText);
					preorderSending = false;
					$('.order li input.obligatory').each(function() {
						if($(this).val() == '')
							$(this).addClass('error');
					});

					console.log('Alla fält är inte ifyllda');

				} else if (data == '3') {

					$('.order #button').text(btnText);
					preorderSending = false;
					$('.order li #email').addClass('error');
					console.log('E-post stämmer inte');

				} else if (data == '4') {

					$('.order #button').text(btnText);
					preorderSending = false;
					$('.order li #postcode').addClass('error');
					console.log('Postnummer stämmer inte');

				} else {
					console.log('Okänt fel.');
				}

			});
		}

	});
	
	function showSuccessMessage() {
		$('.preorderText, #preorderForm').fadeOut();
		$('.order').animate({height: 240});
    	$('#success').animate({height: 240}).fadeIn();
	}

	function hideSuccessMessage() {
    	$('#success').animate({height: 560}).fadeOut();
		$('.order').animate({height: 560});
		$('.preorderText, #preorderForm').fadeIn();
		$('.order input[type=text]').val('');
		preorderSending = false;
	}
	
	$('.order #success .resend').click(function() {
		hideSuccessMessage();
	});

	$('.order #success .close').click(function() {
		$('.order').slideUp('slow');
		$('.order').removeClass('active');
	});
	
	$(window).bind('scroll', function() {
		if($('.order').hasClass('active') && parseInt($('.order').css('height')) > 100) {
			if( $(this).scrollTop() > parseInt($('.order').css('height')) + 150 ) {
				$('.order').animate({'height':'0px'},300);
				$('.order').removeClass('active');
			}
		}
	});
	
	function checkForError(selector, keydown) {
		var emailRegex = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
		var fieldValue = $(selector).val();
		
		if( $(selector).attr('id') == 'company' ) {
			if($(selector).val() === '') {
				$('.order label[for=company] span').fadeOut();
			    $('.order label[for=firstname] span').fadeIn();
			    $('.order label[for=surname] span').fadeIn();
			    $('#company').removeClass('obligatory').removeClass('error');
			    $('#firstname').addClass('obligatory');
			    $('#surname').addClass('obligatory');
				
			} else {
			    $('.order label[for=company] span').fadeIn();
			    $('.order label[for=firstname] span').fadeOut();
			    $('.order label[for=surname] span').fadeOut();
			    $('#company').addClass('obligatory');
			    $('#firstname').removeClass('obligatory').removeClass('error');
			    $('#surname').removeClass('obligatory').removeClass('error');
			}
		}

		if( fieldValue == '' && $(selector).hasClass('obligatory') && keydown == 0) {
			$(selector).addClass('error');
		} else if( $(selector).attr('id') == 'email' && fieldValue != '' && String(fieldValue).search(emailRegex) == -1 && keydown == 0) {
			$(selector).addClass('error');
		} else {
			$(selector).removeClass('error');
		}
	}
	
	$('.order input[type=text]', this).keydown(function() {
		checkForError(this, 1);
	}).blur(function() {
		checkForError(this, 0);
	});

	$('.newEntry label[for=compDescription]').html('Beskrivning (100 tecken återstår) <span>*</span>');
	
	$('.newEntry #compDescription').keyup(function() {
		var text = $('#compDescription').val(); 	
		var textlength = text.length;
	
		if(textlength < 100) {
			$('label[for=compDescription]').html('Beskrivning (' + (100 - textlength) +' tecken återstår) <span>*</span>');
			return true;
		} else {
			$('label[for=compDescription]').html('Beskrivning <span>*</span>');
			return true;
		}
	});

	$('#compUploadAdvanced').css('display', 'none');
	$('#compUploadAdvancedButton').css('display', 'block');
	$('.newEntry #compUploadAdvancedButton').click(function() {
		$(this).slideUp(300);
		$('.newEntry #compUploadAdvanced').delay(300).slideDown();
	});
	
	billboard('#billboard', true, 5000, 'link');
	billboard('#postSlideshow', true, 5000, 'next');
	
	$('.page-template-tavling-senaste-php #preorder').hide();
	
	
	
	linkPostImages();
	animateSearchField();
	tellFriend();
	randomHighlight();
	});
