/* ============================================================================

 ========================
||      SCRIPT.JS      ||
 ========================
	
 Formatted with:

 Sovereign Visual's CodeFlow Framework
 Author: Benjamin Stocks
 http://sovereignvisual.com

==============================================================================

 =======================
||  Table of Contents  ||
 =======================


	1. Featured Work Bar
	



============================================================================== */


/*
 ================================
||     1. Featured Work Bar     ||
 ================================
*/

$(document).ready(function() {
	$('.featured-box').hover(function(){
				$(this).find('.view-button').stop(true, true).fadeIn(100);
				$(this).find('.glow').stop(true, true).fadeIn(300);
				$(this).find('.tab').stop(true, true).animate({bottom:'-5'},{queue:false,duration:300, easing: 'easeOutExpo'});
				$(this).find('.overlay').stop(true, true).fadeIn({duration: 200, queue: false});
			}, function(){
				$(this).find('.view-button').stop(true, true).fadeOut(100);
				$(this).find('.glow').stop(true, true).fadeOut(300);
				$(this).find('.tab').stop(true, true).animate({bottom:'-30px'},{queue:false,duration:150});
				$(this).find('.overlay').stop(true, true).fadeOut({duration: 50, queue: false});
	});
});


/*
 ================================
||     2. Service Features      ||
 ================================
*/

$(function(){
$(".service-icon-container a").tipTip({defaultPosition: "top", delay: 50});
});

/*
 ================================
||     3. Our Work              ||
 ================================
*/


$(document).ready(function() {

	var imgArr = [
					'/images/our-work/avmc1.jpg', 
					'/images/our-work/avmc2.jpg',
					'/images/our-work/avmc3.jpg',
					'/images/our-work/avmc4.jpg',
					'/images/our-work/avmc5.jpg',
					'/images/our-work/baba1.jpg',
					'/images/our-work/baba2.jpg',
					'/images/our-work/baba3.jpg',
					'/images/our-work/baba4.jpg',
					'/images/our-work/dcic1.jpg',
					'/images/our-work/dcic2.jpg',
					'/images/our-work/dcic3.jpg',
					'/images/our-work/jso1.jpg',
					'/images/our-work/jso2.jpg',
					'/images/our-work/jso3.jpg',
					'/images/our-work/jso4.jpg',
					'/images/our-work/bf1.jpg',
					'/images/our-work/sos1.jpg',
					'/images/our-work/sos2.jpg',
					'/images/our-work/sos3.jpg',
					'/images/our-work/co1.jpg',
					'/images/our-work/co2.jpg',
					'/images/our-work/co3.jpg',
					'/images/our-work/co4.jpg',
					'/images/our-work/co5.jpg',
					'/images/our-work/co6.jpg',
					'/images/our-work/awad1.jpg',
					'/images/our-work/awad2.jpg',
					'/images/our-work/awad3.jpg'
					];
	
	loadimages(imgArr);
	
	setTimeout( function(){
				
			if ( !$('#portfolio').hasClass('loaded') ) {
				$('#portfolio .loading-text').fadeOut('fast');
				$('#portfolio .loading-text.too-long').fadeIn('fast');
			}
			
		},10000);
	
	function loadimages(imgArr) {
		//Keep track of the images that are loaded
		var imagesLoaded = 0;
		function loadAllImages(){
			//Create an temp image and load the url
			var img = new Image();
			$(img).attr('src',imgArr[imagesLoaded]);
			if (img.complete || img.readyState === 4) {
				// image is cached
				imagesLoaded++;
				//Check if all images are loaded
				if(imagesLoaded == imgArr.length) {
					//If all images loaded do the callback
					setTimeout( function(){
						$('#portfolio .loading-text').fadeOut(200);
						$('#portfolio').removeClass('loading').addClass('loaded').find('.container_12').fadeIn(300);
					},1000);
				} else {
					//If not all images are loaded call own function again
					loadAllImages();
				}
			} else {
				$(img).load(function(){
					//Increment the images loaded variable
					imagesLoaded++;
					//Check if all images are loaded
					if(imagesLoaded == imgArr.length) {
						//If all images loaded fade in the thumbs
						setTimeout( function(){
							$('#portfolio .loading-text').fadeOut(200);
							$('#portfolio').removeClass('loading').addClass('loaded').find('.container_12').fadeIn(300);
						},1000);
					} else {
						//If not all images are loaded call own function again
						loadAllImages();
					}
				});
			}
		};		
		loadAllImages();
	}
	

	

	$('.portfolio-thumb').click(function(){
		
		if ( $('#portfolio-drawer').hasClass('open').toString() == 'false' ) {
		
			var clientClass = $(this).attr('class').split(' ')[1];
			
			//make sure title container is empty
			$('#title-bar .title-container').empty();
			//clone in correct title
			$('.portfolio-thumb.' + clientClass).find('hgroup').clone().appendTo('#title-bar .title-container');
			//show visit site button if applicable
			$('#title-bar').find('.visit-site.' + clientClass).show();
			
			
			// shameless fix for extra 5px getting mysteriously added to bottom of loader div.
				$('#portfolio-drawer').find('.'+clientClass+' .loader').each(function () {
					var pHeight = $(this).height() - 5;
					$(this).height(pHeight);
				});
			
			$('#title-bar').fadeIn(50).animate({top: 0}, 300, 'easeOutExpo');
			$('#portfolio-footer').fadeIn(50).animate({bottom: 0}, 300, 'easeOutExpo');
			
			$('#portfolio-drawer').addClass('min-height').addClass('open');
			
			bindBackButton(clientClass);
			
			$('#portfolio-drawer').find('.portfolio-content').each(function () {
				var tester = $(this).hasClass(clientClass).toString();
				if ( tester == 'false' )
				{
					$(this).hide();
				}
				else if ( tester == 'true' )
				{
					$(this).show();
				}
				
			});
			
			$('#container').delay(200).fadeOut(300);
			
			$('a[href=#top]').click(function(){

		        $('html, body').animate({scrollTop:0}, 800, 'easeOutExpo');

		        return false;
		        
		    });

			
		}	
	
	});
			    
});


function bindBackButton(clientClass) {

	$('#title-bar').find('.back-button').click( function() {
		
		$('#container').fadeIn(300);
		$('#title-bar').fadeOut(300).animate({top: -117}, 50, 'easeOutExpo');
		$('#portfolio-footer').fadeOut(300).animate({bottom: -77}, 50, 'easeOutExpo');
		
		setTimeout( function(){
				
			$('#portfolio-drawer').find('.portfolio-content').each(function () {
				var tester = $(this).hasClass(clientClass).toString();
				if ( tester == 'false' )
				{
					$(this).hide();
				}
				else if ( tester == 'true' )
				{
					$(this).hide();
				}
				
			});
			
			//hide visit site button if applicable
			$('#title-bar').find('.visit-site.' + clientClass).hide();
			
			$('#portfolio-drawer').removeClass('open').removeClass('min-height');
			
		},500);
		
		
	});
}



/*
 ===============================
||     3. Contact Form         ||
 ===============================
*/

// Show Form on Click
$(document).ready(function() {
	$('#contact-ben .contact-button').click(function() {
		$('#contact-ben').parent().fadeOut(500);
		$('.contact-form.ben').parent().delay(500).fadeIn(1200);
	});
	
	$('#contact-sam .contact-button').click(function() {
		$('#contact-sam').parent().fadeOut(500);
		$('.contact-form.sam').parent().delay(500).fadeIn(1200);
	});
	
});
	
	
//set global variables and cache DOM elements for reuse later
var formBen = $('.contact-form.ben').find('form'),
	formSam = $('.contact-form.sam').find('form'),
	formElementsBen = formBen.find('input[type!="submit"],textarea'),
	formElementsSam = formSam.find('input[type!="submit"],textarea'),
	formSubmitButtonBen = formBen.find('[type="submit"]'),
	formSubmitButtonSam = formSam.find('[type="submit"]'),
	errorNoticeBen = $('.contact-form.ben .errors'),
	errorNoticeSam = $('.contact-form.sam .errors'),
	successNoticeBen = $('.contact-form.ben .success'),
	successNoticeSam = $('.contact-form.sam  .success'),
	errorMessages = {
		required: ' is a required field',
		email: 'You have not entered a valid email address'
	};

//feature detection + polyfills for Ben
formElementsBen.each(function(){

	//if HTML5 input placeholder attribute is not supported
	if(!Modernizr.input.placeholder){
		var placeholderText = this.getAttribute('placeholder');
		if(placeholderText){
			$(this)
				.addClass('placeholder-text')
				.val(placeholderText)
				.bind('focus',function(){
					if(this.value == placeholderText){
						$(this)
							.val('')
							.removeClass('placeholder-text');
					}
				})
				.bind('blur',function(){
					if(this.value == ''){
						$(this)
							.val(placeholderText)
							.addClass('placeholder-text');
					}
				});
		}
	}
	
	//if HTML5 input autofocus attribute is not supported
	if(!Modernizr.input.autofocus){
		if(this.getAttribute('autofocus')) this.focus();
	}
	
});

//feature detection + polyfills for Sam
formElementsSam.each(function(){

	//if HTML5 input placeholder attribute is not supported
	if(!Modernizr.input.placeholder){
		var placeholderText = this.getAttribute('placeholder');
		if(placeholderText){
			$(this)
				.addClass('placeholder-text')
				.val(placeholderText)
				.bind('focus',function(){
					if(this.value == placeholderText){
						$(this)
							.val('')
							.removeClass('placeholder-text');
					}
				})
				.bind('blur',function(){
					if(this.value == ''){
						$(this)
							.val(placeholderText)
							.addClass('placeholder-text');
					}
				});
		}
	}
	
	//if HTML5 input autofocus attribute is not supported
	if(!Modernizr.input.autofocus){
		if(this.getAttribute('autofocus')) this.focus();
	}
	
});


//to ensure compatibility with HTML5 forms, we have to validate the form on submit button click event rather than form submit event. 
//An invalid html5 form element will not trigger a form submit.
//For Ben
formSubmitButtonBen.bind('click',function(){
	var formok = true,
		errors = [];
		
	formElementsBen.each(function(){
		var name = this.name,
			nameUC = name.ucfirst(),
			value = this.value,
			placeholderText = this.getAttribute('placeholder'),
			type = this.getAttribute('type'), //get type old school way
			isRequired = this.getAttribute('required');
		
		//if HTML5 formfields are supported			
		if( (this.validity) && !this.validity.valid ){
			formok = false;
			
			console.log(this.validity);
			
			//if there is a value missing
			if(this.validity.valueMissing){
				errors.push(nameUC + errorMessages.required);	
			}
			//if this is an email input and it is not valid
			else if(this.validity.typeMismatch && type == 'email'){
				errors.push(errorMessages.email);
			}
			
			this.focus(); //safari does not focus element an invalid element
			return false;
		}
		
		//if this is a required element
		if(isRequired){	
			//if HTML5 input required attribute is not supported
			if(!Modernizr.input.required){
				if(value == placeholderText){
					this.focus();
					formok = false;
					errors.push(nameUC + errorMessages.required);
					return false;
				}
			}
		}

		//if HTML5 input email input is not supported
		if(type == 'email'){ 	
			if(!Modernizr.inputtypes.email){ 
				var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
			 	if( !emailRegEx.test(value) ){	
					this.focus();
					formok = false;
					errors.push(errorMessages.email + nameUC);
					return false;
				}
			}
		}
		
	});
	
	//if form is not valid
	if(!formok){
		
		//show error message 
		showNoticeBen('error',errors);
		
	}
	//if form is valid
	else {
		$.ajax({
			url: formBen.attr('action'),
			type: formBen.attr('method'),
			data: formBen.serialize(),
			success: function(){
				showNoticeBen('success');
				formBen.get(0).reset();
			}
		});
		
	}
	
	return false; //this stops submission off the form and also stops browsers showing default error messages.
	
	
});

//to ensure compatibility with HTML5 forms, we have to validate the form on submit button click event rather than form submit event. 
//An invalid html5 form element will not trigger a form submit.
//For Sam
formSubmitButtonSam.bind('click',function(){
	var formok = true,
		errors = [];
		
	formElementsSam.each(function(){
		var name = this.name,
			nameUC = name.ucfirst(),
			value = this.value,
			placeholderText = this.getAttribute('placeholder'),
			type = this.getAttribute('type'), //get type old school way
			isRequired = this.getAttribute('required');
		
		//if HTML5 formfields are supported			
		if( (this.validity) && !this.validity.valid ){
			formok = false;
			
			console.log(this.validity);
			
			//if there is a value missing
			if(this.validity.valueMissing){
				errors.push(nameUC + errorMessages.required);	
			}
			//if this is an email input and it is not valid
			else if(this.validity.typeMismatch && type == 'email'){
				errors.push(errorMessages.email);
			}
			
			this.focus(); //safari does not focus element an invalid element
			return false;
		}
		
		//if this is a required element
		if(isRequired){	
			//if HTML5 input required attribute is not supported
			if(!Modernizr.input.required){
				if(value == placeholderText){
					this.focus();
					formok = false;
					errors.push(nameUC + errorMessages.required);
					return false;
				}
			}
		}

		//if HTML5 input email input is not supported
		if(type == 'email'){ 	
			if(!Modernizr.inputtypes.email){ 
				var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
			 	if( !emailRegEx.test(value) ){	
					this.focus();
					formok = false;
					errors.push(errorMessages.email + nameUC);
					return false;
				}
			}
		}
		
	});
	
	//if form is not valid
	if(!formok){

		//show error message 
		showNoticeSam('error',errors);
		
	}
	//if form is valid
	else {
		$.ajax({
			url: formSam.attr('action'),
			type: formSam.attr('method'),
			data: formSam.serialize(),
			success: function(){
				showNoticeSam('success');
				formSam.get(0).reset();
			}
		});
	}
	
	return false; //this stops submission off the form and also stops browsers showing default error messages
	
});


//other misc functions
function showNoticeBen(type,data)
{
	if(type == 'error'){
		successNoticeBen.hide();
		errorNoticeBen.find("li[class!='info']").remove();
		for(x in data){
			errorNoticeBen.append('<li>'+data[x]+'</li>');	
		}
		errorNoticeBen.show();
	}
	else {
		errorNoticeBen.hide();
		successNoticeBen.show();
		//formBen.parent().delay(1000).fadeOut(300);
		//$('#contact-ben').parent().delay(1300).fadeIn();	
	}
}

//other misc functions
function showNoticeSam(type,data)
{
	if(type == 'error'){
		successNoticeSam.hide();
		errorNoticeSam.find("li[class!='info']").remove();
		for(x in data){
			errorNoticeSam.append('<li>'+data[x]+'</li>');	
		}
		errorNoticeSam.show();
	}
	else {
		errorNoticeSam.hide();
		successNoticeSam.show();
		//formSam.parent().delay(1000).fadeOut(300);
		//$('#contact-sam').parent().delay(1300).fadeIn();
	}
}

String.prototype.ucfirst = function() {
	return this.charAt(0).toUpperCase() + this.slice(1);
}







