// JavaScript Document
//jQuery
$(document).ready(
	function() {
		
		//
		var showreel = {
	 
			//variables
		 
			init:function(){
				
				//Open image
				$('.showreel ul.thumbs li').click(function(event){
					//
					var parent = $(this).closest('div').attr('id');
					var index = $(this).index();
					startReel(parent, index);
					//don't let the html link go
					event.preventDefault();
				});
				
				//Next image
				$('.button-next').click(function(event){
					//
					var parent = $(this).closest('div').attr('id');
					nextImage(parent);
				});
				
				//Previous image
				$('.button-prev').click(function(event){
					//
					var parent = $(this).closest('div').attr('id');
					previousImage(parent);
				});
				
				//Close image
				$('.showreel ul.images li .close').click(function(event){
					//
					var parent = $(this).parent().parent().closest('div').attr('id');
					//
					closeReel(parent);
				});
			}
		};
		
		var currentIndex = 0;
		var showreel;
		var imageCount;
		//
		function startReel(parent, index){
			showreel = parent;
			currentIndex = index;
			imageCount = $('#' + showreel + ' ul.images > li').size();
			
			showImage(index);
		}
		
		
		function closeReel(parent){		
			showreel = parent;
			hideImage(0);
			currentIndex = 0;
		};
		
		//
		function showImage(index){
			
			currentIndex = index;
			
			if (currentIndex >= 0 && currentIndex < imageCount) {

				var image = $('#' + showreel + ' ul.images li').eq(index);
				
				image.css({
					'position' : 'absolute',
					'left' : '0', 'top' : '0'
				});
				
				if (jQuery.support.opacity){ 
					image.fadeIn(300);
				} else {
					image.show();
				};
			
			} else {
				closeReel();
			};
			
		}
		
		//
		function hideImage(wait){
			var image = $('#' + showreel + ' ul.images li').eq(currentIndex);
			
			if (jQuery.support.opacity){
				
				image.delay(wait).fadeOut(300, function(){
					
					image.css({
						'position' : '',
						'left' : '', 'top' : ''
					});
					
				});
				
			} else {
				
				image.hide();
				image.css({
					'position' : '',
					'left' : '', 'top' : ''
				});

			};
			
		}
		
		//
		function nextImage(parent){
			showreel = parent;
			hideImage(100);
			showImage(currentIndex + 1);
		};
		
		function previousImage(parent){
			showreel = parent;
			hideImage(100);
			showImage(currentIndex - 1);
		};
		
		//Initiate showreel
		showreel.init();
		//
		var projectsCount = $('#case-studies ul.images > li').size();
		currentIndex = Math.floor(Math.random()*projectsCount)
		startReel('case-studies', currentIndex);
		
		//FEEDBACK TAB
		var feedbackTab = {
	 
			speed:300,
			slide:'335px',
		 
			init:function(){
				
				$('#feedback-tab').css('height', '290px');
		 
				$('#feedback-tab h3').click(function(event){
					if ($('#feedback-tab').hasClass('open')) {
						$('#feedback-tab')
						.animate({left:'-' + feedbackTab.slide}, feedbackTab.speed)
						.removeClass('open');
					} else {
						$('#feedback-tab')
						.animate({left:'0'}, feedbackTab.speed)
						.addClass('open');
					}
					event.preventDefault();
				});
			}
		};
		 
		feedbackTab.init();
		
		//Header close
		var header = {
			
			bigger:'504px',
			smaller:'144px',
			speed:300,
			
			init:function(){
				
				$('#button-header').click(function(event){
					
					toggleHeader();
					
				});
			}
		};
		
		function toggleHeader() {
			if ( $('#header').hasClass('open') ) {
				//close
				$('#header')
				.animate({ height:header.smaller }, header.speed,
				function() {
					$('#header').removeClass('open').addClass('closed');
				});
				
			} else {
				//open
				$('#header').animate({ height:header.bigger }, header.speed,
				function() {
					$('#header').removeClass('closed').addClass('open');
				});

			}
		}
		
		header.init();
		
		//Replace Form field values on focus
		var valArray = new Array();
		
		function getValues(){
			$('input[type="text"]').each(function(){
				var value = $(this).attr('value');
				valArray.push(value);
			});
		};
		getValues();
		
		$('input[type="text"]').focus(function(){
			var index = $('input[type="text"]').index(this);
			var value = $(this).attr('value');
			if (value == valArray[index]){
				$(this).attr('value', '');	
			}
			
		});
		
		$('input[type="text"]').blur(function(){
			var index = $('input[type="text"]').index(this);
			var value = $(this).attr('value');
			if (value == ''){
				$(this).attr('value', valArray[index]);	
			}
		});
		
		/*
		//News pod onclick action
		$(".news-pod").click(
							 
			function() {
				window.location = $(this).find("h3:first a:first").attr("href");
			}
		);
		*/
		
		/*

		* jYoutube 1.0 - YouTube video image getter plugin for jQuery
		*
		* Copyright (c) 2009 jQuery Howto
		*
		* Licensed under the GPL license:
		*   http://www.gnu.org/licenses/gpl.html
		*
		* Plugin home & Author URL:
		*   http://jquery-howto.blogspot.com
		*
		*/
		(function($){
		$.extend({
			jYoutube: function( url, size ){
				if(url === null){ return ""; }
		
				size = (size === null) ? "big" : size;
				var vid;
				var results;
		
				results = url.match("[\\?&]v=([^&#]*)");
		
				vid = ( results === null ) ? url : results[1];
		
				if(size == "small"){
					return "http://img.youtube.com/vi/"+vid+"/2.jpg";
				}else {
					return "http://img.youtube.com/vi/"+vid+"/0.jpg";
				}
			}
		})
		})(jQuery);
		
	/********************************************************************************/
	/*	CONTACT FORM VALIDATION AND SUBMIT	::::::::::::::::::::::::::::::::::::::::*/
	/********************************************************************************/
	//Check if fields are valid and add valid or invalid class (call functions)
	$('input[class=form-name]').bind('click change focus keypress', function() {
		checkBasic($(this));		
	});
	
	$('textarea[class=form-message]').bind('click change focus keypress', function() {
		checkBasic($(this));		
	});
	
	$('input[class=form-email]').bind('click change focus keypress', function() {
		checkEmail($(this));
	});
	$('select[class=form-subject]').bind('click change focus keypress', function() {
		checkSubject($(this));
	});
	
	//Functions to check fields
	
	function checkBasic(field){
		if (field.attr('value').length != '0' && field.attr('value') != 'Nome' ){
			field.removeClass('invalid')
			return false;			
		}
		else {
			field.addClass('invalid');
			return true;
		}
	}
	function checkEmail(field){
		if (emailValidation(field.attr('value'))){
			field.removeClass('invalid')
			return false;			
		}
		else {
			field.addClass('invalid');
			return true;
		}
	}
	function checkSubject(field){
		if (field.attr('value') != 'Escolha o assunto'){
			field.removeClass('invalid')
			return false;			
		}
		else {
			field.addClass('invalid');
			return true;
		}
	}

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

	function validForm(form){
		var errors = new Array();
		errors[0] = checkBasic( $('#' + form + ' .form-name') );
		errors[1] = checkEmail( $('#' + form + ' .form-email') );
		errors[2] = checkSubject( $('#' + form + ' .form-subject') );
		errors[3] = checkBasic( $('#' + form + ' .form-message') );
		
		var invalid = jQuery.inArray(true, errors);
		if (invalid != -1 && invalid != undefined ) {
			return true;
		}
	}
	
	//Submit contact form actions
	
	$('#contact-submit').click(function(){
		//check if form is valid
		if (!validForm('contact-form')){
			//disable button to avoid double submit
			//$('#contact-submit').attr('disabled', 'disabled');
			var form = $('#contact-form');
			$.post(
				'wp-content/themes/bile/mail/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
					alert( stripTags(response) );
				}
				//dataType	The type of data expected from the server (text, xml, json)
			);
		} else {
			//Show invalid message
			alert('Por favor preencha correctamente todos os campos e tente novamente.');
		}
		return false;
	});
	
		//Submit feedback form actions
	
	$('#feedback-submit').click(function(){
		//check if form is valid
		if (!validForm('feedback-tab')){
			//disable button to avoid double submit
			//$('#contact-submit').attr('disabled', 'disabled');
			var form = $('#feedback-tab');
			$.post(
				'wp-content/themes/bile/mail/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(response, status, request){
					// do something with response
					alert( stripTags(response) );
				}
				//dataType	The type of data expected from the server (text, xml, json)
			);
		} else {
			//Show invalid message
			alert('Por favor preencha correctamente todos os campos e tente novamente.');
			
		}
		return false;
	});
	
	//
	function stripTags( string ){
		
		return string.replace(/(<([^>]+)>)/ig,"");
	}

	 
	//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);
	}
	
	//CONTACT BUDGET FORM
	$('#contact-budget-form h4').click(function(){
		$('#contact-budget-form form > h4').removeClass();
		$('#contact-budget-form form > div.wrap').addClass('hide');
		//alert( $(this).attr('class') );
		if( $(this).attr('class') != 'selected' ){
			$(this).addClass('selected');
			$(this).next('div').removeClass('hide');
		}
	});
		
		

	//End jQuery
	}
); 

