//jQuery
$(document).ready(function(){
	
	//Check if fields are valid and add valid or invalid class (call functions)
	
	$('input[type=text]').bind('click focus keypress', function() {
		if ($(this).attr('value').toLowerCase() == $(this).attr('name')) $(this).attr('value', '');
	});
	
	$('input[class=required]').bind('click focus keypress', function() {
		checkBasic($(this));
	});
	
	$('input[name=puhelin]').bind('click focus keypress', function() {
		if ($(this).attr('value') == 'Puhelin') $(this).attr('value', '');
		checkPhone($(this));
	});	
	
	$('input[name=sahkoposti]').bind('click focus keypress', function() {
		if ($(this).attr('value') == 'Sahkoposti') $(this).attr('value', '');
		checkEmail($(this));
	});
	
	$('input[name=kiinnostus]:radio').bind('click focus blur keypress', function() {
		if ($(this).attr('id') == 'kiinnostus1'){
			$('#fieldset-jasenyys').removeClass('hide');
			$('#fieldset-vapaasana').removeClass('hide');
		}
		else {
			$('#fieldset-jasenyys').addClass('hide');	
			$('#fieldset-vapaasana').addClass('hide');	
		}				
	});
	
	$('input[name=jasenyys]:radio').bind('click focus blur keypress', function() {
		if ($(this).attr('id') != 'jasenyys1'){
			$('#fieldset-where').removeClass('hide');
		}
		else {
			$('#fieldset-where').addClass('hide');
		}			
	});

	$('input[name=vapaasana]').bind('click focus keypress', function() {
		checkBasic($(this));
	});

	//function that validates all fields of the form and return true if an error is encountered

	function validForm(){
		var errors = new Array();
		errors[0] = checkBasic( $('input[id=nimi]') );
		errors[1] = checkBasic( $('input[id=ika]') );
		errors[2] = checkPhone( $('input[id=puhelin]') );
		errors[3] = checkBasic( $('input[id=osoite]') );
		errors[4] = checkEmail( $('input[id=sahkoposti]') );
		
		errors[5] = checkBasic( $('input[id=koti]') );
		
		errors[6] = checkRadio( $('input[name=kiinnostus]:checked') );
		
		if (errors[6] == false && $('input[name=kiinnostus]:checked').attr('id') == 'kiinnostus1'){
			errors[7] = checkRadio( $('input[name=jasenyys]:checked') );
			if (errors[7] == false && $('input[name=jasenyys]:checked').attr('id') != 'jasenyys1'){
				errors[8] = checkBasic( $('input[id=missa]') );		
			}
			if ($('textarea[id=vapaasana]').attr('value') != "") { errors[9] = false; } else { errors[9] = true; }
		}
		var invalid = jQuery.inArray(true, errors);
		
		if (invalid != -1 && invalid != undefined ) {
			return true;
		}
	}
	
	//Functions to check fields
	
	function checkBasic(field){
		if (field.attr('value').length != '0' && field.attr('name') != field.attr('value').toLowerCase() ){
			field.removeClass('invalid');
			field.addClass('valid');
			return false;			
		}
		else {
			field.removeClass('valid');
			field.addClass('invalid');
			return true;
		}
	}
	function checkPhone(field){
		if (phoneValidation(field.attr('value'))){
			field.removeClass('invalid');
			field.addClass('valid');
			return false;			
		}
		else {
			field.removeClass('valid');
			field.addClass('invalid');
			return true;
		}
	}
	function checkEmail(field){
		if (emailValidation(field.attr('value'))){
			field.removeClass('invalid');
			field.addClass('valid');
			return false;			
		}
		else {
			field.removeClass('valid');
			field.addClass('invalid');
			return true;
		}
	}
	function checkRadio(field) {
		if (field.length != '0'){
			return false;			
		}
		else {
			return true;
		}
	}
	
	//Submit Button actions
	
	$('#lottery-form').submit(function() {
		//check if form is valid
		if (!validForm()){
			//disable button to avoid double submit
			//$('#contact-submit').attr('disabled', 'disabled');
			var form = $(this);
			$.post(
				'wp-content/themes/kunnonsali/sendmail.php',	//url	A string containing the URL to which the request is sent
				form.serialize(),									//data	A map or string that is sent to the server with the request.
				//success	A callback function that is executed if the request succeeds
				function(data, status, request){
					// do something with response
					outputMessage(data);
				}
				//dataType	The type of data expected from the server (text, xml, json)
			);
		} else {
			//Show invalid message
			alert('Error');
		}
		return false;
	});

	//Function that outputs the string given by the post result
	function outputMessage(data){
		var response = data.split(',');
		var status = response[0];
		if (status == 'success') {
			var message = response[1];
			alert(message);
		}
		else {
			var message = response[1];
			alert(message);
		}
	}
	 
	//Aditional functions to validate specific fields
	
	function emailValidation (email){
		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pattern.test(email);
	}

	function phoneValidation( phone ) {
		//check phone number
		var filter = /^[0-9 +() + -]+$/;
		return filter.test(phone);
	}
	
	/****** BANNER *******/
	
	//ROUND CORNNERS HACK http://www.bram.us/sandbox/roundedcorners/
	$('#banner img').each(function() {
		$(this).wrap( '<span style="background-image:url(' + $(this).attr('src') + ');" class="rounded" />' );
	});
	
	//BANNER
	var selectedIndex = 0;
	var sti = 0;
	var adsCount = $('.banner-ad').size();
	var fadeSpeed = 1000;
	var switchInt = 8000;
	
	$('#banner-nav a').click( function(event){
		
		switchBanner( $(this).index('#banner-nav a') );
		resumeBanner();
		
		event.preventDefault();
	});
	
	$('#banner-nav a').hover(
		function () {
			$(this).addClass('selected');
		},
		function () {
			if( $(this).index('#banner-nav a') != selectedIndex ){
				$(this).removeClass('selected');
			}
		}
	);

	
	function switchBanner( index ) {
		
		$('#banner-nav a').eq( selectedIndex ).removeClass('selected');
		$('.banner-ad').eq( selectedIndex ).fadeOut('fast');
		
		if ( index >= adsCount ) {
			index = 0;
		}
		selectedIndex = index ;
		
		$('#banner-nav a').eq( selectedIndex ).addClass('selected');
		$('.banner-ad').eq( selectedIndex ).fadeIn(fadeSpeed);
		
	}
	
	function resumeBanner() {
		clearInterval ( sti );
		sti = setInterval( function(){ switchBanner( selectedIndex + 1 ) }, switchInt );
	}
	
	function startBanner() {
		if ( adsCount > 1 ) {
			$('#banner-nav a').eq( 0 ).addClass('selected');
			resumeBanner();
		}
	}
	startBanner();
	
	/****** CALENDAR *******/
	/*
	Get the current weekday
	*/
	var date = new Date();
	var weekday = date.getDay();
	if (weekday == 0) { weekday = 7; }
	
	showDay();
	compactContent();
	/*
	Check which calendar-nav li element was clicked and:
		Remove the today class from the elements
		Add the today class to the today's element
		
		Add the hide class to the week-lessons li elements
		Remove the hide class to today's week-lessons li element
	*/
	$('#calendar-nav li').bind('click', function(event) {
		
		$('#calendar-nav').children().each(function(){
			if($(this).hasClass('today')){
				$(this).removeClass('today');
			}
		});
		
		if(!$(this).hasClass('today')){
			$(this).addClass('today');
		}
		
		var lesson_day = ($(this).index() + 1);
		$('#week-lessons li').each(function(){
			if($(this).hasClass('hide') == false){
				$(this).addClass('hide');
			}
		});
		$('#week-lessons li:nth-child(' + lesson_day + ')').removeClass('hide');
		event.preventDefault();
	});
	
	/*
	Check which calendar-buttons element has clicked and do some stuff
	*/	
	$('#calendar-buttons span').bind('click', function(){
		/*
		If clicked calendar-buttons element is the close button, toggle the hide class to some elements
		*/	
		if ($(this).hasClass('close-button')){
			if($('#week-lessons').hasClass('hide') == true){
				expandContent(); //showDay();
				$('#calendar-buttons span:eq(1)').removeClass('hide');
				$('#next-lesson').addClass('hide');
				$('#week-lessons').removeClass('hide');
				$('#calendar-nav').removeClass('hide');
				//
				$('#calendar-buttons .close-button').removeClass('open');
				$('#calendar-buttons .close-button').addClass('close');
				$('#calendar-buttons .close-button').attr('title', 'Sulje aikataulu'); //Close schedule
			}
			else {
				$('#calendar-buttons span:eq(1)').addClass('hide');
				$('#week-lessons').addClass('hide');
				$('#calendar-nav').addClass('hide');
				$('#next-lesson').removeClass('hide');
				//
				$('#calendar-buttons .close-button').removeClass('close');
				$('#calendar-buttons .close-button').addClass('open');
				$('#calendar-buttons .close-button').attr('title', 'Avaa aikataulu'); //Open schedule
			}
		}
		
		/*
		If clicked calendar-buttons element is the expand button, compact or expand the content and toggle the expanded class
		*/	
		if ($(this).hasClass('expand-button')){
			if ($(this).hasClass('expanded')){
				$(this).removeClass('expanded');
				compactContent();
				$(this).attr('title', 'Katso koko pÃ¤ivÃ¤'); //See full day
			}
			else {
				$(this).addClass('expanded');
				expandContent();
				$(this).attr('title', 'Kutista aikataulu'); //Shrink schedule
			}
		}
		
	});
	
	
	/*
	Get the number of lessons of each day, the next lesson and hide all the lessons, then execute the switch
	*/
	function compactContent(){
		
		var number_lessons, next_lesson;

		$('#week-lessons li').each(function(){
			
			number_lessons = ($('table tr', $(this)).length - 1);
			$('table tr', $(this)).each(function(){
				
				if ($(this).hasClass('today')){
					next_lesson = $(this).index();
				}	
				if (!$(this).hasClass('hide')){
					$(this).addClass('hide');
				}
				
			});
			/*
			Show the lessons in agree with the following specs:
				next_lesson is the first lesson: exec the first case
				next_lesson is the penultimate lesson: exec the second case
				next_lesson is the last lesson: exec the third case
				next_lesson is none of the above: exec the default
			*/			
			switch(next_lesson){
				case (0) :
					$('table tr:eq(' + next_lesson + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson + 1) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson + 2) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson + 3) + ')', $(this)).removeClass('hide');
					break;
				case (number_lessons - 1) :
					$('table tr:eq(' + (next_lesson - 2) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson - 1) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson + 1) + ')', $(this)).removeClass('hide');
					break;							
				case (number_lessons) :
					$('table tr:eq(' + (next_lesson - 3) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson - 2) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson - 1) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson) + ')', $(this)).removeClass('hide');
					break;
				default :
					$('table tr:eq(' + (next_lesson - 1) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson + 1) + ')', $(this)).removeClass('hide');
					$('table tr:eq(' + (next_lesson + 2) + ')', $(this)).removeClass('hide');
					break;							
			}				
		});
	}
	
	function expandContent(){
		
		/*
		Remove the hide class from all the lessons of all the days
		*/		
		$('#week-lessons li').each(function(){
			$('table tr', $(this)).each(function(){
				if ($(this).hasClass('hide')){
					$(this).removeClass('hide');
				}
				
			});
		});
	}


	function showDay(){
		
		/*
		Remove all the today class from all the #calendar-nav li elements
		*/		
		$('#calendar-nav li').each(function(){
			if($(this).hasClass('today') == true){
				$(this).removeClass('today');
			}
		});

		/*
		Add to all #week-lessons li elements the hide class
		*/		
		$('#week-lessons li').each(function(){
			if($(this).hasClass('hide') == false){
				$(this).addClass('hide');
			}
		});
		
		/*
		Add Class to today's calendar-nav element
		Remove the hide class from today's lesson
		*/
		
		$('#calendar-nav li:nth-child(' + weekday + ')').addClass('today');
		$('#week-lessons li:nth-child(' + weekday + ')').removeClass('hide');
				
	}
	
	//
	$('#calendar .class-content').bind('click', function(event) {
		var link = $(this).children('a').attr('href');
		window.location = link;
	});
	
	/*END JQUERY*/

});
//END JQUERY

function trace( msg ){
  if( typeof( jsTrace ) != 'undefined' ){
    jsTrace.send( msg );
  }
}

//

try {
	document.execCommand('BackgroundImageCache', false, true);
}
catch(e) {}

//

var bool = true;
	
function openbox(id){
	
	var boxdiv = document.getElementById( id );
	var boxclass = boxdiv.className;
		
	if(bool == false) {
		boxclass = "hide";
		bool = true;
	} else {
		boxclass = "";
		bool = false;
	}
	
	boxdiv.className = boxclass;

}

//

var pfDiv;
var flashDiv;
var blogDiv;
var isClosed = true;

function onButtonPress(folioBtn){
	
	var bodyWidth = document.body.offsetWidth;
	var maxWidth = bodyWidth * 0.7;
	
	pfDiv = document.getElementById('portfolio');
	blogDiv = document.getElementById('blog');
	flashDiv = document.getElementById('portfolio-container');
	
	var openTween = new Tween(pfDiv.style,'width',Tween.strongEaseOut,2,70,0.5,'%');
	var closeTween = new Tween(pfDiv.style,'width',Tween.strongEaseOut,maxWidth,22,0.5,'px');
	
	if(isClosed && folioBtn) {
		
		blogDiv.style.display = "none";
		openTween.start();
		flashDiv.openPortfolio();
		isClosed = false;
		
	} else if (folioBtn){
		
		closeTween.start();
		flashDiv.openPortfolio();
		isClosed = true;
		
	}
	
	if(!isClosed && !folioBtn) {
		
		closeTween.start();
		flashDiv.openPortfolio();
		isClosed = true;
		
	}
	
	closeTween.onMotionFinished = function(){
		blogDiv.style.display = "block";
	};
	
	//trace(maxWidth);
}



function fieldFocus(field){
	
	var fieldAuthor = document.getElementById('author');
	var fieldEmail = document.getElementById('email');
	var fieldUrl = document.getElementById('url');
	
	if (fieldAuthor.value == "") {
		fieldAuthor.value = "Nome";
	} else if (fieldAuthor.value == "Nome" && field == "author"){
		fieldAuthor.value = "";
	}
	
	if (fieldEmail.value == "") {
		fieldEmail.value = "E-mail";
	} else if (fieldEmail.value == "E-mail" && field == "email"){
		fieldEmail.value = "";
	}
	
	if (fieldUrl.value == "") {
		fieldUrl.value = "Website";
	} else if (fieldUrl.value == "Website" && field == "url"){
		fieldUrl.value = "";
	}
}
